SpringBoot中怎么集成Redis

本篇文章为大家展示了Spring Boot中怎么集成redis,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

创新互联公司:于2013年开始为各行业开拓出企业自己的“网站建设”服务,为上1000家公司企业提供了专业的成都网站制作、做网站、网页设计和网站推广服务, 按需求定制网站由设计师亲自精心设计,设计的效果完全按照客户的要求,并适当的提出合理的建议,拥有的视觉效果,策划师分析客户的同行竞争对手,根据客户的实际情况给出合理的网站构架,制作客户同行业具有领先地位的。

添加依赖

使用像 Redis 这类的 NOSQL 数据库就必须要依赖 spring-data-redis 这样的能力包,开箱即用,Spring Boot 中都封装好了:

引入spring-boot-starter-data-redis:

   org.springframework.boot   spring-boot-starter-data-redis  

Spring Boot 基础知识就不介绍了,不熟悉的可以关注公众号Java技术栈,在后台回复:boot,可以阅读我写的历史实战教程。

它主要包含了下面四个依赖:

  •  spring-boot-dependencies

  •  spring-boot-starter

  •  spring-data-redis

  •  lettuce-core

添加 Redis 连接配置

Redis 自动配置支持配置单机、集群、哨兵,来看下 RedisProperties 的参数类图吧:

Spring Boot中怎么集成Redis

本文以单机为示例,我们在 application.yml 配置文件中添加 Redis 连接配置,:

spring:    redis:      host: 192.168.8.88      port: 6379      password: redis2020      database: 1

也可以将参数配置在 Spring Cloud Config Server 配置中心中。

Redis 自动配置

添加完依赖和连接配置参数之后,Redis 就能自动配置,参考 Redis 的自动配置类:

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内置两种客户端的自动配置:

1)Lettuce(默认):

org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration

2)Jedis:

org.springframework.boot.autoconfigure.data.redis.JedisConnectionConfiguration

为什么默认Lettuce,其实文章之前的四个依赖也看出来了,请看默认依赖:

Spring Boot中怎么集成Redis

自动配置提供了两种操作模板:

1)RedisTemplate

key-value 都为 Object 对象,并且默认用的 JDK 的序列化/反序列化器:

org.springframework.data.redis.serializer.JdkSerializationRedisSerializer

使用这个序列化器,key 和 value 都需要实现 java.io.Serializable 接口。

2)StringRedisTemplate

key-value 都为 String 对象,默认用的 String UTF-8 格式化的序列化/反序列化器:

org.springframework.data.redis.serializer.StringRedisSerializer

上面提到了两种序列化器,另外还有两种 JSON 的序列化器值得学习一下,下面配置会用到。

  •  Jackson2JsonRedisSerializer

  •  GenericJackson2JsonRedisSerializer

使用方式上,两种都可以序列化、反序列化 JSON 数据,Jackson2JsonRedisSerializer 效率高,但 GenericJackson2JsonRedisSerializer 更为通用,不需要指定泛型类型。

核心配置

除了自动配置之外,下面是 Redis 的核心配置,主要是自定义了 RedisTemplate 使用 JSON 序列化器。

另外就是,把几个数据类型的操作类进行了 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();      }  }

如果你只想用默认的 JDK 序列化器,那 RedisTemplate 相关配置就不是必须的。

缓存实战

下面写了一个示例,用来缓存并读取缓存中一个类对象。

@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,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。


网站题目:SpringBoot中怎么集成Redis
路径分享:http://pwwzsj.com/article/ipjsjd.html