Spring Boot 2.X(六):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.在项目中添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>cn.zwqh</groupId>
<artifactId>spring-boot-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-redis</name>
<description>spring-boot-redis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
查看 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 线程池设置 ##############
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
自定义 RedisTemplate
默认情况下的模板只能支持 RedisTemplate<String,String>
,只能存入字符串,很多时候,我们需要自定义 RedisTemplate ,设置序列化器,这样我们可以很方便的操作实例对象。如下所示:
@Configuration
public class LettuceRedisConfig {
@Bean
public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Serializable> 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)
@SpringBootTest
public class SpringBootRedisApplicationTests {
@Autowired
private RedisTemplate<String, String> strRedisTemplate;
@Autowired
private RedisTemplate<String, Serializable> 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 文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>cn.zwqh</groupId>
<artifactId>spring-boot-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-redis</name>
<description>spring-boot-redis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<!-- 排除lettuce包 -->
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加jedis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
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 线程池设置 ##############
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.jedis.pool.min-idle=0
JedisRedisConfig
@Configuration
public 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 RedisTemplate<String, Serializable> redisTemplate(JedisConnectionFactory connectionFactory) {
RedisTemplate<String, Serializable> 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 2.X(六):Spring Boot 集成Redis
原文地址: https://www.zwqh.top/article/info/11
如果文章对您有帮助,请扫码关注下我的公众号,文章持续更新中...

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
Java虚拟机线上问题排查的2个基本操作,你知不知道?
前言 对于后端程序员,特别是 Java 程序员来讲,排查线上问题是不可避免的。各种 CPU 飚高,内存溢出,频繁 GC 等等,这些都是令人头疼的问题。楼主同样也遇到过这些问题,那么,遇到这些问题该如何解决呢?首先,出现问题,肯定要先定位问题所在,然后分析问题原因,再然后解决问题,最后进行总结,防止下次再次出现。今天的文章,就如我们的题目一样,讲的是基本操作,也就是一些排查线上问题的基本方法。为什么这么说呢?因为线上问题千奇百怪,就算是身经百战的专家也会遇到棘手的问题,因此不可能在一篇文章里说完,还有一个最重要的原因,当然就是楼主的水平不到位。但不到位归不到位,任何经验都是值得记录的,因此,楼主有必要将这些问题记录一下。还有,本文的排查环境是 Linux. CPU 飚高 线上 CPU 飚高问题大家应该都遇到过,那么如何定位问题呢?思路:首先找到 CPU 飚高的那个 Java 进程,因为你的服务器会有多个 JVM 进程。然后找到那个进程中的 “问题线程”,最后根据线程堆栈信息找到问题代码。最后对代码进行排查。如何操作呢?通过 top 命令找到 CPU 消耗最高的进程,并记住进程 ID。再次...
-
下一篇
Spring Boot 2.X(七):Spring Cache 使用
Spring Cache 简介 在 Spring 3.1 中引入了多 Cache 的支持,在 spring-context 包中定义了org.springframework.cache.Cache 和 org.springframework.cache.CacheManager 两个接口来统一不同的缓存技术。Cache 接口包含缓存的常用操作:增加、删除、读取等。CacheManager 是 Spring 各种缓存的抽象接口。Spring 支持的常用 CacheManager 如下: CacheManager 描述 SimpleCacheManager 使用简单的 Collection 来存储缓存 ConcurrentMapCacheManager 使用 java.util.ConcurrentHashMap 来实现缓存 NoOpCacheManager 仅测试用,不会实际存储缓存 EhCacheCacheManger 使用EhCache作为缓存技术。EhCache 是一个纯 Java 的进程内缓存框架,特点快速、精干,是 Hibernate 中默认的 CacheProvider,也是...
相关文章
文章评论
共有0条评论来说两句吧...