新聞中心
Spring Boot 如何快速集成 Redis?沒錯(cuò),棧長本文教你,讓大家少走彎路!

汝城網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)建站!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)建站從2013年開始到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)建站。
添加依賴
使用像 Redis 這類的 NoSQL 數(shù)據(jù)庫就必須要依賴 spring-data-redis 這樣的能力包,開箱即用,Spring Boot 中都封裝好了:
引入spring-boot-starter-data-redis:
org.springframework.boot spring-boot-starter-data-redis
Spring Boot 基礎(chǔ)知識(shí)就不介紹了,不熟悉的可以關(guān)注公眾號(hào)Java技術(shù)棧,在后臺(tái)回復(fù):boot,可以閱讀我寫的歷史實(shí)戰(zhàn)教程。
它主要包含了下面四個(gè)依賴:
- spring-boot-dependencies
- spring-boot-starter
- spring-data-redis
- lettuce-core
添加 Redis 連接配置
Redis 自動(dòng)配置支持配置單機(jī)、集群、哨兵,來看下 RedisProperties 的參數(shù)類圖吧:
本文以單機(jī)為示例,我們在 application.yml 配置文件中添加 Redis 連接配置,:
- spring:
- redis:
- host: 192.168.8.88
- port: 6379
- password: redis2020
- database: 1
也可以將參數(shù)配置在 Spring Cloud Config Server 配置中心中。
Redis 自動(dòng)配置
添加完依賴和連接配置參數(shù)之后,Redis 就能自動(dòng)配置,參考 Redis 的自動(dòng)配置類:
- org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
源碼:
- @Configuration(proxyBeanMethods = false)
- @ConditionalOnClass(RedisOperations.class)
- @EnableConfigurationProperties(RedisProperties.class)
- @Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
- public class RedisAutoConfiguration {
- ...
- }
通過看源碼,Redis內(nèi)置兩種客戶端的自動(dòng)配置:
1)Lettuce(默認(rèn)):
- org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration
2)Jedis:
- org.springframework.boot.autoconfigure.data.redis.JedisConnectionConfiguration
為什么默認(rèn)Lettuce,其實(shí)文章之前的四個(gè)依賴也看出來了,請(qǐng)看默認(rèn)依賴:
自動(dòng)配置提供了兩種操作模板:
1)RedisTemplate
key-value 都為 Object 對(duì)象,并且默認(rèn)用的 JDK 的序列化/反序列化器:
- org.springframework.data.redis.serializer.JdkSerializationRedisSerializer
使用這個(gè)序列化器,key 和 value 都需要實(shí)現(xiàn) java.io.Serializable 接口。
2)StringRedisTemplate
key-value 都為 String 對(duì)象,默認(rèn)用的 String UTF-8 格式化的序列化/反序列化器:
- org.springframework.data.redis.serializer.StringRedisSerializer
上面提到了兩種序列化器,另外還有兩種 JSON 的序列化器值得學(xué)習(xí)一下,下面配置會(huì)用到。
- Jackson2JsonRedisSerializer
- GenericJackson2JsonRedisSerializer
使用方式上,兩種都可以序列化、反序列化 JSON 數(shù)據(jù),Jackson2JsonRedisSerializer 效率高,但 GenericJackson2JsonRedisSerializer 更為通用,不需要指定泛型類型。
核心配置
除了自動(dòng)配置之外,下面是 Redis 的核心配置,主要是自定義了 RedisTemplate 使用 JSON 序列化器。
另外就是,把幾個(gè)數(shù)據(jù)類型的操作類進(jìn)行了 Bean 池化處理。
- @Configuration
- public class RedisConfig {
- @Bean
- public RedisTemplate
redisTemplate(RedisConnectionFactory factory) { - RedisTemplate
template = new RedisTemplate<>(); - template.setConnectionFactory(factory);
- StringRedisSerializer stringSerializer = new StringRedisSerializer();
- RedisSerializer jacksonSerializer = getJacksonSerializer();
- template.setKeySerializer(stringSerializer);
- template.setValueSerializer(jacksonSerializer);
- template.setHashKeySerializer(stringSerializer);
- template.setHashValueSerializer(jacksonSerializer);
- template.setEnableTransactionSupport(true);
- template.afterPropertiesSet();
- return template;
- }
- private RedisSerializer getJacksonSerializer() {
- ObjectMapper om = new ObjectMapper();
- om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
- om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
- return new GenericJackson2JsonRedisSerializer(om);
- }
- @Bean
- public HashOperations
hashOperations(RedisTemplate redisTemplate) { - return redisTemplate.opsForHash();
- }
- @Bean
- public ValueOperations
valueOperations(RedisTemplate redisTemplate) { - return redisTemplate.opsForValue();
- }
- @Bean
- public ListOperations
listOperations(RedisTemplate redisTemplate) { - return redisTemplate.opsForList();
- }
- @Bean
- public SetOperations
setOperations(RedisTemplate redisTemplate) { - return redisTemplate.opsForSet();
- }
- @Bean
- public ZSetOperations
zSetOperations(RedisTemplate redisTemplate) { - return redisTemplate.opsForZSet();
- }
- }
如果你只想用默認(rèn)的 JDK 序列化器,那 RedisTemplate 相關(guān)配置就不是必須的。
緩存實(shí)戰(zhàn)
下面寫了一個(gè)示例,用來緩存并讀取緩存中一個(gè)類對(duì)象。
- @GetMapping("/redis/set")
- public String set(@RequestParam("name") String name) {
- User user = new User();
- user.setId(RandomUtils.nextInt());
- user.setName(name);
- user.setBirthday(new Date());
- List
list = new ArrayList<>(); - list.add("sing");
- list.add("run");
- user.setInteresting(list);
- Map
map = new HashMap<>(); - map.put("hasHouse", "yes");
- map.put("hasCar", "no");
- map.put("hasKid", "no");
- user.setOthers(map);
- redisOptService.set(name, user, 30000);
- User userValue = (User) redisOptService.get(name);
- return userValue.toString();
- }
測試:
http://localhost:8080/redis/set?name=zhangsan
返回:
- User(id=62386235, name=zhangsan, birthday=Tue Jun 23 18:04:55 CST 2020, interesting=[sing, run], others={hasHouse=yes, hasKid=no, hasCar=no})
Redis中的值:
- 192.168.8.88:6379> get zhangsan "["cn.javastack.springboot.redis.pojo.User",{"id":62386235,"name":"zhangsan","birthday":["java.util.Date",1592906695750],"interesting":["java.util.ArrayList",["sing","run"]],"others":["java.util.HashMap",{"hasHouse":"yes","hasKid":"no","hasCar":"no"}]}]"
好啦,Spring Boot 快速集成 Redis 就到這了,下篇帶來 Spring Boot 如何快速集成 Redis 分布式鎖,關(guān)注公眾號(hào)Java技術(shù)棧,第一時(shí)間推送,敬請(qǐng)期待……
本文完整源代碼也將和下篇一起上傳到Github,歡迎大家 Star 關(guān)注學(xué)習(xí)。
https://github.com/javastacks/spring-boot-best-practice
分享名稱:SpringBoot如何快速集成Redis?
標(biāo)題來源:http://fisionsoft.com.cn/article/dhhocgi.html


咨詢
建站咨詢
