上一篇文章,簡單記錄了一下緩存的使用方法,這篇文章將把我們熟悉的redis整合進來。
那么如何去整合呢?首先需要下載和安裝,為了使用方便,也可以做環境變量的配置。
下載和安裝的方法,之前有介紹,在docker中的使用,這里不做相關介紹,有想在windows環境下使用的,自己搜一下如何windows安裝使用redis吧~(看這里也可以)
正題: SpringBoot對應(自帶)RedisClient是不同的
SpringBoot1.5.x版本 -> jedis
SpringBoot2.x版本 - > lettuce (本文以2.x為例)
Redis啟動與應用
啟動redis服務,並打開管理客戶端。其中默認的端口號,可以通過修改config來實現。
按照如圖所示的步驟,鏈接本地的redis,如果你是在遠程服務器安裝的,ip記得填寫服務器的。
選中我們做好的鏈接,右鍵打開console或者ctrl+T,打開控制台,我們來測試一下命令是否可用~
在控制台輸入命令,看一下(Redis命令點擊查看)
繼續輸入命令,可以看到字符串會相應的做拼接,這就是追加key值的命令的作用。其他命令,自己可以去試一下~
整合到SpringBoot中
接下來,我們將這個redis整合到SpringBoot中來,首先,在pom.xml中添加
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
1.配置redis:到配置文件中添加:(如果是遠程服務器,自己替換IP)
spring.redis.host=127.0.0.1
添加好以后我們來測試一下,首先,為了存取數據到redis中,添加如下的代碼,我們接着看這兩個如何使用。
@Autowired StringRedisTemplate stringRedisTemplate; // k-v都是字符串 @Autowired RedisTemplate redisTemplate; // k-v都是對象
先看字符串的,跟之前在console中輸入命令一樣的作用,執行測試后,檢查下redis中,確實有生成的msg,說明我們的關聯和操作是成功的。
stringRedisTemplate.opsForValue().append("msg", "Hello"); //append中添加的是兩個字符串,也就是上邊的k-v字符串操作
所以,你該明白第二個k-v是對象的意思了吧?繼續測試方法中這樣寫:(我們將查詢的這個對象存到緩存中)
Employee empById = employeeMapper.getEmpById(1);
redisTemplate.opsForValue().set("emp-01", empById);
來看結果:(Cannot serialize表示無法序列化,這里先看下如何處理,稍后來說為什么以及如何優化)
我們將bean.Employee的類這樣寫,就可以保證基本的序列化: implements Serializable
public class Employee implements Serializable {xxxx}
再次運行,查看結果:(運行成功了,可這一堆亂碼一樣的是什么呢?)
其實默認的序列化是JDK的,我們需要自己優化一下,比如編程json的序列化。
來看如何優化呢,我們需要自己創建一個redis的配置,來序列化我們自己想要的json格式(其實就是把RedisAutoConfiguration中的方法拿出來稍微的修改一下)
注意,我把主程序中的@EnableCaching,放到這里了,主程序那里就不用寫了?后邊我們再來實驗一下
import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.time.Duration; @Configuration @EnableCaching public class MyRedisConfig { @Bean public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1)) // 設置緩存有效期一小時 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer( new GenericJackson2JsonRedisSerializer())); // 設置json格式序列化 return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } }
然后使用我們自己建立的template方法,做一個測試,看下結果:(注解證明木有問題)
Employee empById = employeeMapper.getEmpById(1);
employeeRedisTemplate.opsForValue().set("emp-01", empById);
是不是看起來舒服多了。
當然,如果我們針對不同的情況做不同的書寫有時候也是必要的,所以也可以這樣寫:(new那一行,看下變化,你就知道了~),但記住,如果你有多個個性配置的時候要加入注解@Primary,這個可以讓該bean作為默認的主緩存管理器來使用,不然會報錯滴~
@Bean public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1)) // 設置緩存有效期一小時 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer( new Jackson2JsonRedisSerializer<Employee>(Employee.class))); // 設置json格式序列化 return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); }
如上,redis的簡單使用就說這些,后邊我可能還會把文章擴展一下,具體說說怎么使用,盡請關注~