最近在学习Spring Boot 2.x整合Redis,在这里和大家分享一下,希望对大家有帮助。
Redis是什么
Redis 是开源免费高性能的key-value数据库。有以下的优势(源于Redis官网):
-
性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
-
丰富的数据类型 – Redis支持二进制案例的 Strings,Lists,Hashes,Sets 及 Ordered Sets 数据类型操作。
-
原子 – Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来。
-
丰富的特性 – Redis还支持 publish/subscribe,通知,key 过期等等特性。
为什么要使用Redis
- 性能:如果碰到需要执行耗时特别久,且结果不频繁变动的SQL,就特别适合将运行结果放入缓存。这样,后面的请求就去缓存中读取,使得请求能够迅速响应。
- 并发: 在大并发的情况下,所有的请求直接访问数据库,数据库会出现连接异常。这个时候,就需要使用redis做一个缓冲操作,让请求先访问到Redis,而不是直接访问数据库。
为什么要使用Redis来自博客园 ,这篇博文关于Redis的讲解我觉得超赞,谢谢作者的耐心分享。
Spring Boot 2.x如何整合Redis
我使用的Spring Boot版本是2.1.0,根据网上的一些旧的教程进行整合Redis 3.2的时候,会有许多地方有错误提示。这是因为Spring Boot 2.x做了一些修改,这些修改对使用而有没有影响呢?我们改怎么整合呢?下面就进入正式的整合过程。
1. pom.xnl引入依赖
现在会提示Project build error: 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-redis:jar is missing. 提示spring-boot-starter-redis:jar找不到。
这是因为Spring Boot 1.4之后不再支持,更换之后就可以了。如果你的pom文件报错,请检查是否将spring-boot-starter-redis 改成了spring-boot-starter-data-redis。
Spring Boot 2.x要使用下面的依赖:
2. application.properties添加配置文件
这是之前版本的配置文件:
如果Spring Boot 2.x这么配置,有错误提示 Property 'spring.redis.pool.max-active' is Deprecated: Use 'spring.redis.jedis.pool.max-idle' instead. ''已经被弃用了,推荐使用''来代替。
这是因为在2.x中配置redis的连接池信息时,不再使用spring.redis.pool的属性,而是直接使用redis的lettuce或jedis客户端来配置。现在的配置如下:
3. 配置CacheManager
这是之前的RedisConfig配置类:
@Bean
</span><span style="color: #0000ff;">public</span> RedisTemplate<String,String><span style="color: #000000;"> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate</span><String,String> redisTemplate = <span style="color: #0000ff;">new</span> RedisTemplate<String,String><span style="color: #000000;">();
redisTemplate.setConnectionFactory(factory);
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> redisTemplate;
}
}
现在这么写会有报错The constructor RedisCacheManager(RedisTemplate
这是因为Spring Boot 2.x版本删除了RedisCacheManager这个构造器, 也不可以通过之前的setDefaultExpiration方法设置默认的缓存过期时间等。
那么要怎样构造一个 RedisCacheManager?看看官方文档中怎么说?文档地址:
官方文档5.13.1. Support for the Spring Cache Abstraction(对Spring Cache Abstraction的支持)是关于怎么配置缓存的说明,我尝试着翻译了一下(蓝色部分),英文水平有限,各位轻喷。
Spring Redis provides an implementation for the Spring through the org.springframework.data.redis.cache package. To use Redis as a backing implementation,add RedisCacheManager to your configuration,as follows:
RedisCacheManager behavior can be configured with RedisCacheManagerBuilder,letting you set the default RedisCacheConfiguration,transaction behavior,and predefined caches.
As shown in the preceding example,RedisCacheManager allows definition of configurations on a per-cache basis.
The behavior of RedisCache created with RedisCacheManager is defined with RedisCacheConfiguration. The configuration lets you set key expiration times,prefixes,and RedisSerializer implementations for converting to and from the binary storage format,as shown in the following example:
RedisCacheManager defaults to a lock-free RedisCacheWriter for reading and writing binary values. Lock-free caching improves throughput. The lack of entry locking can lead to overlapping,non-atomic commands for the putIfAbsent and clean methods,as those require multiple commands to be sent to Redis. The locking counterpart prevents command overlap by setting an explicit lock key and checking against presence of this key,which leads to additional requests and potential command wait times.
It is possible to opt in to the locking behavior as follows:
By default,any key for a cache entry gets prefixed with the actual cache name followed by two colons. This behavior can be changed to a static as well as a computed prefix.
The following example shows how to set a static prefix:
RedisCacheConfiguration.defaultCacheConfig().computePrefixWith(cacheName -> "¯_(ツ)_/¯" + cacheName);
The following table lists the default settings for RedisCacheManager:
@Bean
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config </span>= RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(1<span style="color: #000000;">));
RedisCacheManager cacheManager </span>=<span style="color: #000000;"> RedisCacheManager.builder(factory).cacheDefaults(config).build();
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> cacheManager;
}
}
4. Service层
在这里仅创建一个简单的RedisService,来进行存取缓存数据。
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> Object get(String key) {
ValueOperations</span><String,Object> vo =<span style="color: #000000;"> redisTemplate.opsForValue();
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> vo.get(key);
}
}
5. Model层
实体类没有修改,和之前文章里面用的一样:
</span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> <span style="color: #0000ff;">long</span> serialVersionUID = 1L<span style="color: #000000;">;
@Id
@GeneratedValue
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> Long id;
@Column(name </span>= "username"<span style="color: #000000;">)
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> String userName;
@Column(name </span>= "password"<span style="color: #000000;">)
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> String passWord;
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> User() {
</span><span style="color: #0000ff;">super</span><span style="color: #000000;">();
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> User(String userName,String passWord) {
</span><span style="color: #0000ff;">super</span><span style="color: #000000;">();
</span><span style="color: #0000ff;">this</span>.userName =<span style="color: #000000;"> userName;
</span><span style="color: #0000ff;">this</span>.passWord =<span style="color: #000000;"> passWord;
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> User(Long id,String userName,String passWord) {
</span><span style="color: #0000ff;">super</span><span style="color: #000000;">();
</span><span style="color: #0000ff;">this</span>.id =<span style="color: #000000;"> id;
</span><span style="color: #0000ff;">this</span>.userName =<span style="color: #000000;"> userName;
</span><span style="color: #0000ff;">this</span>.passWord =<span style="color: #000000;"> passWord;
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> Long getId() {
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> id;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setId(Long id) {
</span><span style="color: #0000ff;">this</span>.id =<span style="color: #000000;"> id;
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String getUserName() {
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> userName;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setUserName(String userName) {
</span><span style="color: #0000ff;">this</span>.userName =<span style="color: #000000;"> userName;
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String getPassWord() {
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> passWord;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setPassWord(String passWord) {
</span><span style="color: #0000ff;">this</span>.passWord =<span style="color: #000000;"> passWord;
}
}
6. Controller层
@Autowired
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> RedisService redisService;
@RequestMapping(</span>"/saveUser"<span style="color: #000000;">)
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String saveUser(Long id,String passWord) {
User user </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> User(id,userName,passWord);
redisService.set(id </span>+ ""<span style="color: #000000;">,user);
</span><span style="color: #0000ff;">return</span> "success"<span style="color: #000000;">;
}
@RequestMapping(</span>"/getUserById"<span style="color: #000000;">)
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> User getUserById(Long id) {
User res </span>= (User) redisService.get(id + ""<span style="color: #000000;">);
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> res;
}
}