javascript
redis序列化_SpringBoot整合redis
redis是最常用的緩存數據庫,常用于存儲用戶登錄token、臨時數據、定時相關數據等。
redis是單線程的,所以redis的操作是原子性的,這樣可以保證不會出現并發問題。
redis基于內存,速度非常快,據測試,redis讀的速度是110000次/s,寫的速度是81000次/s
本節介紹SpringBoot引入redis,以及使用RedisTemplate來操作redis數據。
采用SpringBoot 2.1.9.RELEASE,對應示例代碼在:https://github.com/laolunsi/spring-boot-examples
一、A Simple Demo-使用SpringBoot連接redis
maven:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency>yml:
server:port: 8867 spring:redis:host: localhostport: 6379#password: ''database: 6測試類:
@SpringBootTest @RunWith(SpringRunner.class) public class RedisTest {@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void testRedis() {String key = "hello";redisTemplate.opsForValue().set("hello", "你好");String res = (String) redisTemplate.opsForValue().get(key);System.out.println(res);} }執行結果:
看一下redis:
這里存在一個問題:默認的存儲方式導致key在redis-manager里面顯示出來是亂碼的,并且存儲結果是二進制了。這樣不利用我們查看redis里面的數據。
我們需要自定義redis存儲的序列化規則。
二、解決RedisTemplate默認序列化的問題
完善一下maven:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId> </dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope> </dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency>定義RedisConfig類:
/*** redis配置* 主要是配置Redis的序列化規則,替換默認的jdkSerializer* key的序列化規則用StringRedisSerializer* value的序列化規則用Jackson2JsonRedisSerializer*/ @Configuration public class RedisConfig {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);// 使用Jackson2JsonRedisSerialize替換默認序列化Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper = new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objectMapper);// 設置key和value的序列化規則redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;} }刪除之前的key,重新執行一下test方法:
下面來演示一下SpringBoot使用RedisTemplate進行redis數據的操作
三、基于SpringBoot的redis操作——key/list/hash
RedisTemplate內置redis操作如下:
這里主要展示value/hash/list三種用法:
3.1 RedisTemplate.opsForValue
@Testpublic void testKeyOps() {// 測試redis操作key-value形式Set<String> keySet = new HashSet<>();String key1 = "name";keySet.add(key1);// 存儲簡單的key-value,并設置過期時間redisTemplate.opsForValue().set(key1, "eknown", 1, TimeUnit.MINUTES);String key2 = "token:user1";String key3 = "token:user2";keySet.add(key2);keySet.add(key3);//redisTemplate.opsForValue().set(key2, "{"name":"eknown"}, "role":"admin"");redisTemplate.opsForValue().set(key3, "{"name":"test"}, "role":"test"");// 根據key的集合獲取多個valueList<String> valueList = redisTemplate.opsForValue().multiGet(keySet);for (String value : valueList) {System.out.println(value);}}執行結果:
redis中的數據:
redis中的key顯示出了一個層級關系,這個小技巧對于實際項目有個非常好的作用:通過prefix:suffix這樣的形式,可以將redis中存儲的數據分出層級。
3.2 RedisTemplate.opsForHash
清空該database下的數據,測試redisTemplate.opsForHash:
@Testpublic void testHashOps() {String key = "hash";// 單次往hash中存放一個數據redisTemplate.opsForHash().put(key, "1", "你好");Map<String, Object> map = new HashMap<>();map.put("2", "hello");map.put("3a", "china1=2");// 一次性向hash中存放一個mapredisTemplate.opsForHash().putAll(key, map);// 獲取hash下的所有key和valueMap<String, Object> resultMap = redisTemplate.opsForHash().entries(key);for (String hashKey : resultMap.keySet()) {System.out.println(hashKey + ": " + resultMap.get(hashKey));}}執行結果:
redis:
3.3 RedisTemplate.opsForList
@Testpublic void testListOps() {String listKey = "list";redisTemplate.opsForList().leftPush(listKey, "first value"); // 從list最左邊插入數據redisTemplate.opsForList().leftPush(listKey, "second value but left");redisTemplate.opsForList().rightPush(listKey, 3); // 從list最右邊插入數據List<Object> list = new ArrayList<>();list.add("hello");list.add("http://www.eknown.cn");list.add(23344);list.add(false);redisTemplate.opsForList().rightPushAll(listKey, list); // 從list右邊批量插入數據long size = redisTemplate.opsForList().size(listKey);if (size > 0) {for (int i = 0; i < size -1 ; i++) {// 從list最左邊開始讀取list中的數據,注意pop會導致出棧,也就是數據被取出來了(redis中就沒有這個值了)// 此處我們讀取size-1條數據,僅留下最后一條數據System.out.println(i + ":" + redisTemplate.opsForList().leftPop(listKey).toString());}}}執行上面的腳本,注意在最后的讀取list數據代碼前面加一個斷點,此時redis中是這樣的:
放開斷點,程序繼續執行,控制臺如下:
注意,此時redis中僅剩余最后一條數據,這是由于pop的問題,list中的數據被讀取并刪除了:
好了,這一節主要講了SpringBoot引入redis,以及使用redis的一些基本操作和相關技巧,在此基礎上,我們可以讓我們的項目變得更加快速、靈活!
交流學習
我的個人網站:http://www.eknown.cn
Git倉庫地址:https://github.com/laolunsi
另外也歡迎大家關注我的公眾號:猿生物語,一起學習Java/SpringBoot/SpringCloud技術。
總結
以上是生活随笔為你收集整理的redis序列化_SpringBoot整合redis的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: ei会议论文录用但不参加会议_美国研究生
- 下一篇: linux关机命令_Linux基于cen
