Springboot如何操作redis數(shù)據(jù)
StringRedisTemplate與RedisTemplate區(qū)別點
兩者的關(guān)系是StringRedisTemplate繼承RedisTemplate。
兩者的數(shù)據(jù)是不共通的;也就是說StringRedisTemplate只能管理StringRedisTemplate里面的數(shù)據(jù),RedisTemplate只能管理RedisTemplate中的數(shù)據(jù)。
其實他們兩者之間的區(qū)別主要在于他們使用的序列化類:
RedisTemplate使用的是JdkSerializationRedisSerializer 存入數(shù)據(jù)會將數(shù)據(jù)先序列化成字節(jié)數(shù)組然后在存入Redis數(shù)據(jù)庫。
StringRedisTemplate使用的是StringRedisSerializer
使用時注意事項:
當(dāng)你的redis數(shù)據(jù)庫里面本來存的是字符串?dāng)?shù)據(jù)或者你要存取的數(shù)據(jù)就是字符串類型數(shù)據(jù)的時候,那么你就使用
StringRedisTemplate即可。
但是如果你的數(shù)據(jù)是復(fù)雜的對象類型,而取出的時候又不想做任何的數(shù)據(jù)轉(zhuǎn)換,直接從Redis里面取出一個對象,那么使用
RedisTemplate是更好的選擇。
RedisTemplate使用時常見問題:
redisTemplate 中存取數(shù)據(jù)都是字節(jié)數(shù)組。當(dāng)redis中存入的數(shù)據(jù)是可讀形式而非字節(jié)數(shù)組時,使用redisTemplate取值的時候會無法獲取導(dǎo)出數(shù)據(jù),獲得的值為null。可以使用 StringRedisTemplate 試試。
RedisTemplate中定義了5種數(shù)據(jù)結(jié)構(gòu)操作
redisTemplate.opsForValue();//操作字符串 redisTemplate.opsForHash(); //操作hash redisTemplate.opsForList(); //操作list redisTemplate.opsForSet(); //操作set redisTemplate.opsForZSet(); //操作有序setStringRedisTemplate常用操作
stringRedisTemplate.opsForValue().set('test', '100',60*10,TimeUnit.SECONDS);//向redis里存入數(shù)據(jù)和設(shè)置緩存時間 stringRedisTemplate.boundValueOps('test').increment(-1);//val做-1操作 stringRedisTemplate.opsForValue().get('test')//根據(jù)key獲取緩存中的val stringRedisTemplate.boundValueOps('test').increment(1);//val +1 stringRedisTemplate.getExpire('test')//根據(jù)key獲取過期時間 stringRedisTemplate.getExpire('test',TimeUnit.SECONDS)//根據(jù)key獲取過期時間并換算成指定單位 stringRedisTemplate.delete('test');//根據(jù)key刪除緩存 stringRedisTemplate.hasKey('546545');//檢查key是否存在,返回boolean值 stringRedisTemplate.opsForSet().add('red_123', '1','2','3');//向指定key中存放set集合 stringRedisTemplate.expire('red_123',1000 , TimeUnit.MILLISECONDS);//設(shè)置過期時間 stringRedisTemplate.opsForSet().isMember('red_123', '1')//根據(jù)key查看集合中是否存在指定數(shù)據(jù) stringRedisTemplate.opsForSet().members('red_123');//根據(jù)key獲取set集合StringRedisTemplate的使用
springboot中使用注解@Autowired 即可
@Autowiredpublic StringRedisTemplate stringRedisTemplate;
使用樣例:
@RestController@RequestMapping('/user')public class UserResource { private static final Logger log = LoggerFactory.getLogger(UserResource.class); @Autowired private UserService userService; @Autowired public StringRedisTemplate stringRedisTemplate; @RequestMapping('/num') public String countNum() { String userNum = stringRedisTemplate.opsForValue().get('userNum'); if(StringUtils.isNull(userNum)){ stringRedisTemplate.opsForValue().set('userNum', userService.countNum().toString()); } return userNum; }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
