Spring Boot怎样集成Redis
本篇文章给大家分享的是有关Spring Boot怎样集成Redis,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
Redis 简介
什么是 Redis
Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库。
Redis 与其他 key-value 缓存(如 Memcached )相比有以下三个特点:
1.Redis 支持数据的持久化,它可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。 2.Redis 不仅仅支持简单的 key-value 类型的数据,同时还提供 list,set,zset,hash 等数据结构的存储。 3.Redis 支持数据的备份,即 master-slave 模式的数据备份。
Redis 优势如下:
1.性能极高。Redis 能读的速度是 110000 次/s,写的速度是 81000 次/s。 2.丰富的数据类型。Redis 支持二进制案例的 Strings,Lists,Sets 及 Ordered Sets 数据类型操作。 3.原子性。Redis 所有的操作都是原子性的,意思是要么成功执行要么失败完全不执行。单个操作是原子性的,多个操作也是,通过 MULTI 和 EXEC 指令抱起来。 4.丰富的特性。Redis 还支持 publish/subscribe,通知,key 过期等特性。
Spring Boot 集成 Redis
1.在项目中添加依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.9.RELEASE cn.zwqh spring-boot-redis 0.0.1-SNAPSHOT spring-boot-redis spring-boot-redis 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-maven-plugin
查看 jar 包时发现,Spring Data Redis 下 org.springframework.data.redis.connection 包路径下面默认有两个包 jedis 和 lettuce,这说明 Spring Boot 已经默认包装适配了这两个 Redis 客户端。
在 springboot 1.5.x版本的默认的Redis客户端是 Jedis实现的,springboot 2.x版本中默认客户端是用 lettuce实现的。
Lettuce 与 Jedis 比较
Lettuce 和 Jedis 的都是连接 Redis Server的客户端。
Jedis 在实现上是直连 redis server,多线程环境下非线程安全,除非使用连接池,为每个 redis实例增加物理连接。
Lettuce 是 一种可伸缩,线程安全,完全非阻塞的Redis客户端,多个线程可以共享一个RedisConnection,它利用Netty NIO 框架来高效地管理多个连接,从而提供了异步和同步数据访问方式,用于构建非阻塞的反应性应用程序。
下面我们分别使用 Lettuce 和 Jedis 来集成 Redis 服务
2. Lettuce 集成 Redis 服务
导入依赖
由于 Spring Boot 2.X 默认集成了 Lettuce ,所以无需导入。
application.properties配置文件
################ Redis 基础配置 ############### Redis数据库索引(默认为0)spring.redis.database=0 # Redis服务器地址spring.redis.host=127.0.0.1# Redis服务器连接端口spring.redis.port=6379 # Redis服务器连接密码(默认为空)spring.redis.password=zwqh# 链接超时时间 单位 ms(毫秒)spring.redis.timeout=3000################ Redis 线程池设置 ############### 连接池最大连接数(使用负值表示没有限制) 默认 8spring.redis.lettuce.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1spring.redis.lettuce.pool.max-wait=-1# 连接池中的最大空闲连接 默认 8spring.redis.lettuce.pool.max-idle=8# 连接池中的最小空闲连接 默认 0spring.redis.lettuce.pool.min-idle=0
自定义 RedisTemplate
默认情况下的模板只能支持 RedisTemplate
,只能存入字符串,很多时候,我们需要自定义 RedisTemplate ,设置序列化器,这样我们可以很方便的操作实例对象。如下所示:
@Configurationpublic class LettuceRedisConfig { @Bean public RedisTemplateredisTemplate(LettuceConnectionFactory connectionFactory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate; }}
序列化实体类
public class UserEntity implements Serializable { /** * */ private static final long serialVersionUID = 5237730257103305078L; private Long id; private String userName; private String userSex; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } }
单元测试
@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringBootRedisApplicationTests { @Autowired private RedisTemplatestrRedisTemplate; @Autowired private RedisTemplate serializableRedisTemplate; @Test public void testString() { strRedisTemplate.opsForValue().set("strKey", "zwqh"); System.out.println(strRedisTemplate.opsForValue().get("strKey")); } @Test public void testSerializable() { UserEntity user=new UserEntity(); user.setId(1L); user.setUserName("朝雾轻寒"); user.setUserSex("男"); serializableRedisTemplate.opsForValue().set("user", user); UserEntity user2 = (UserEntity) serializableRedisTemplate.opsForValue().get("user"); System.out.println("user:"+user2.getId()+","+user2.getUserName()+","+user2.getUserSex()); }}
执行结果如下: 得到我们预期的结果。
3.Jedis 集成 Redis 服务
pom 文件
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.9.RELEASE cn.zwqh spring-boot-redis 0.0.1-SNAPSHOT spring-boot-redis spring-boot-redis 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-data-redis io.lettuce lettuce-core redis.clients jedis org.springframework.boot spring-boot-maven-plugin
application.properties配置文件
################ Redis 基础配置 ############### Redis数据库索引(默认为0)spring.redis.database=0 # Redis服务器地址spring.redis.host=127.0.0.1# Redis服务器连接端口spring.redis.port=6379 # Redis服务器连接密码(默认为空)spring.redis.password=zwqh# 链接超时时间 单位 ms(毫秒)spring.redis.timeout=3000################ Redis 线程池设置 ############### 连接池最大连接数(使用负值表示没有限制) 默认 8spring.redis.jedis.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1spring.redis.jedis.pool.max-wait=-1# 连接池中的最大空闲连接 默认 8spring.redis.jedis.pool.max-idle=8# 连接池中的最小空闲连接 默认 0spring.redis.jedis.pool.min-idle=0
JedisRedisConfig
@Configurationpublic class JedisRedisConfig { @Value("${spring.redis.database}") private int database; @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.jedis.pool.max-active}") private int maxActive; @Value("${spring.redis.jedis.pool.max-wait}") private long maxWaitMillis; @Value("${spring.redis.jedis.pool.max-idle}") private int maxIdle; @Value("${spring.redis.jedis.pool.min-idle}") private int minIdle; /** * 连接池配置信息 */ @Bean public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 最大连接数 jedisPoolConfig.setMaxTotal(maxActive); // 当池内没有可用连接时,最大等待时间 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); // 最大空闲连接数 jedisPoolConfig.setMinIdle(maxIdle); // 最小空闲连接数 jedisPoolConfig.setMinIdle(minIdle); // 其他属性可以自行添加 return jedisPoolConfig; } /** * Jedis 连接 * * @param jedisPoolConfig * @return */ @Bean public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) { JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling() .poolConfig(jedisPoolConfig).and().readTimeout(Duration.ofMillis(timeout)).build(); RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(host); redisStandaloneConfiguration.setPort(port); redisStandaloneConfiguration.setPassword(RedisPassword.of(password)); return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration); } /** * 缓存管理器 * * @param connectionFactory * @return */ @Bean public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { return RedisCacheManager.create(connectionFactory); } @Bean public RedisTemplateredisTemplate(JedisConnectionFactory connectionFactory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(jedisConnectionFactory(jedisPoolConfig())); return redisTemplate; }}
单元测试同上
出现预期结果。
上面介绍了 Spring Boot 2.X 如何通过 Lettuce 和 Jedis 来集成 Redis 服务,按项目需求,我们也可以自定义操作类来实现数据操作。
以上就是Spring Boot怎样集成Redis,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。