SpringBoot整合redis

网友投稿 820 2022-05-29

Spring Data Redis介绍

Spring Data Redis 是更大的 Spring Data 系列的一部分,它提供了从 Spring 应用程序对 Redis 的轻松配置和访问。它提供了与商店交互的低级和高级抽象,使用户摆脱了对基础设施的担忧。

SpringBoot2.x版本,其内置的Redis中间件再也不是Jedis了,而是换成了lettuce。

lettuce: Lettuce 是 一种可伸缩,线程安全,完全非阻塞的Redis客户端,多个线程可以共享一个RedisConnection,它利用Netty NIO 框架来高效地管理多个连接,从而提供了异步和同步数据访问方式,用于构建非阻塞的反应性应用程序。

Jedis: Jedis 在实现上是直连 redis server,多线程环境下非线程安全,除非使用连接池,为每个 redis实例增加 物理连接。 这种方式更加类似于我们 BIO 一条线程连一个客户端,并且是阻塞式的,会一直连接着客户端等待客户端的命令

官方文档:https://docs.spring.io/spring-data/redis/docs/current/reference/html/#reference

引依赖

SpringBoot整合redis

org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 com.fasterxml.jackson.core jackson-core

写配置-对于连接的管理

spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.database=0 #超时时间 spring.redis.timeout= 1800000 # 连接池最大连接数 spring.redis.lettuce.pool.max-active= 20 # 最大阻塞等待时间 spring.redis.lettuce.pool.max-wait=-1 # 连接池的最大空闲连接 spring.redis.lettuce.pool.max-idle=5 # 连接池的最小空闲连接 spring.redis.lettuce.pool.min-idle=0

配置类-做序列化的设置

import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; 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.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; /** * redis配置类,对key,value进行序列化 * * @author Promsing(张有博) * @version 1.0.0 * @since 2022/5/6 - 16:49 */ @EnableCaching @Configuration public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate template = new RedisTemplate<>(); RedisSerializer redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 template.setValueSerializer(jackson2JsonRedisSerializer); //value hashmap序列化 template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解决乱码的问题),过期时间600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) //设置数据过期时间600秒 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }

简单使用redis

package com.promsing.redis.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 测试redis的操作 * * @author Promsing(张有博) * @version 1.0.0 * @since 2022/5/6 - 16:56 */ @RestController @RequestMapping("redis") public class RedisController { @Autowired private RedisTemplate redisTemplate; @GetMapping public String saveRedis(){ redisTemplate.opsForValue().set("springboot:redis:name","promsing"); Object o = redisTemplate.opsForValue().get("springboot:redis:name"); System.out.println("redis中存储的内容"+o); return o.toString(); } }

其他测试方法

@RunWith(SpringRunner.class) @SpringBootTest(classes = UserApplication.class) public class RedisTest { @Autowired private StringRedisTemplate redisTemplate;//存储的数据进行了序列化,建议使用它 private RedisTemplate redisTemplate2;//存储的数据没有给序列化 @Test public void testRedis() { // 存储数据 this.redisTemplate.opsForValue().set("key2", "value2"); // 获取数据 String val = this.redisTemplate.opsForValue().get("key2"); System.out.println("val = " + val); } @Test public void testRedis2() { // 存储数据,并指定剩余生命时间,5小时 this.redisTemplate.opsForValue().set("key2", "value2", 5, TimeUnit.HOURS); } @Test public void testHash() { BoundHashOperations hashOps = this.redisTemplate.boundHashOps("user"); // 操作hash数据 hashOps.put("name", "jack"); hashOps.put("age", "21"); // 获取单个数据 Object name = hashOps.get("name"); System.out.println("name = " + name); // 获取所有数据 Map map = hashOps.entries(); for (Map.Entry me : map.entrySet()) { System.out.println(me.getKey() + " : " + me.getValue()); } } }

Redis Spring Boot

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java开发规约
下一篇:《Word/Excel/PPT 2019完全自学教程 : 视频讲解版 》 —1.2.2 设置开始屏幕显示的文档数量
相关文章