Spring Boot 2.x整合Redis
最近在学习Spring Boot 2.x整合Redis,在这里和大家分享一下,希望对大家有帮助。 Redis是什么Redis 是开源免费高性能的key-value数据库。有以下的优势(源于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添加配置文件这是之前版本的配置文件: =0=127.0.0.1=6379=-active=8-wait=-1-idle=8-idle=0=0
如果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客户端来配置。现在的配置如下: =0=127.0.0.1=6379=-active=8-wait=-1-idle=8-idle=0=0
3. 配置CacheManager这是之前的RedisConfig配置类: RedisConfig CacheManager cacheManager(RedisTemplate,?>=
@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.
RedisCacheManager cm ="predefined"
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:
RedisCacheConfiguration config =1
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:
RedisCacheManager cm =
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().prefixKeysWith("( ?° ? ?°)"The following example shows how to set a computed prefix:
<span style="color: #008000;">//<span style="color: #008000;"> computed key prefix
RedisCacheConfiguration.defaultCacheConfig().computePrefixWith(cacheName -> "ˉ_(ツ)_/ˉ" + cacheName); The following table lists the default settings for RedisCacheManager:
RedisConfig
@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层添加缓存逻辑的时候,从数据库中将内容读取出来之后,先set入缓存,然后再从缓存中添加读取行为,如果缓存为空则从数据库中进行读取。
在这里仅创建一个简单的RedisService,来进行存取缓存数据。 RedisTemplate
</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层实体类没有修改,和之前文章里面用的一样: = "user" User
</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层在user.Controller添加两个测试方法,一个写入Redis,一个从Redis读取:
"user"
@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;
}
} 7. 测试使用Postman进行测试,访问,添加了一个User。 ,通过id获取User。 这是过滤器和拦截器的日志信息,可以看到没有进行MySQL数据库的操作,直接从缓存中读取,说明Redis配置生效了: 以上就是Spring Boot 2.x整合Redis的全过程,和Spring Boot之前的版本在使用上有些细微的差别。
本文水平有限,或多或少有欠妥之处,还望各位大佬指正!
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |