加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Spring Boot 2.x整合Redis

发布时间:2020-12-15 01:53:09 所属栏目:大数据 来源:网络整理
导读:最近在学习Spring Boot 2.x整合Redis,在这里和大家分享一下,希望对大家有帮助。 Redis是什么 Redis 是开源免费高性能的key-value数据库。有以下的优势(源于Redis官网): 性能极高?– Redis能读的速度是110000次/s,写的速度是81000次/s 。 丰富的数据类型
Setting Value Cache Writer Non-locking Cache Configuration RedisCacheConfiguration#defaultConfiguration Initial Caches None Trasaction Aware No The following table lists the default settings for RedisCacheConfiguration:

最近在学习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

  1. 性能:如果碰到需要执行耗时特别久,且结果不频繁变动的SQL,就特别适合将运行结果放入缓存。这样,后面的请求就去缓存中读取,使得请求能够迅速响应。
  2. 并发: 在大并发的情况下,所有的请求直接访问数据库,数据库会出现连接异常。这个时候,就需要使用redis做一个缓冲操作,让请求先访问到Redis,而不是直接访问数据库。

为什么要使用Redis来自博客园?,这篇博文关于Redis的讲解我觉得超赞,谢谢作者的耐心分享。

Spring Boot 2.x如何整合Redis

我使用的Spring Boot版本是2.1.0,根据网上的一些旧的教程进行整合Redis 3.2的时候,会有许多地方有错误提示。这是因为Spring Boot 2.x做了一些修改,这些修改对使用而有没有影响呢?我们改怎么整合呢?下面就进入正式的整合过程。

1. pom.xnl引入依赖

这是之前的依赖:
org.springframework.boot spring-boot-starter-redis

现在会提示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要使用下面的依赖:

org.springframework.boot spring-boot-starter-data-redis

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;"&gt;public</span> RedisTemplate<String,String><span style="color: #000000;"&gt; redisTemplate(RedisConnectionFactory factory) { RedisTemplate</span><String,String> redisTemplate = <span style="color: #0000ff;"&gt;new</span> RedisTemplate<String,String><span style="color: #000000;"&gt;(); redisTemplate.setConnectionFactory(factory); </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; redisTemplate; }

}

现在这么写会有报错The constructor RedisCacheManager(RedisTemplate) is undefined。

这是因为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:

Key Expiration None Cache null Yes Prefix Keys Yes Default Prefix The actual cache name Key Serializer StringRedisSerializer Value Serializer JdkSerializationRedisSerializer Conversion Service DefaultFormattingConversionService with default cache key converters 对于Spring Boot 2.x,这里我使用简单配置一下缓存时间,完成RedisCacheManager的配置,代码如下:

RedisConfig @Bean </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config </span>= RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(1<span style="color: #000000;"&gt;)); RedisCacheManager cacheManager </span>=<span style="color: #000000;"&gt; RedisCacheManager.builder(factory).cacheDefaults(config).build(); </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; cacheManager; }

}

4. Service层

添加缓存逻辑的时候,从数据库中将内容读取出来之后,先set入缓存,然后再从缓存中添加读取行为,如果缓存为空则从数据库中进行读取。

在这里仅创建一个简单的RedisService,来进行存取缓存数据。

RedisTemplate RedisSerializer redisSerializer = vo =</span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; Object get(String key) { ValueOperations</span><String,Object> vo =<span style="color: #000000;"&gt; redisTemplate.opsForValue(); </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; vo.get(key); }

}

5. Model层

实体类没有修改,和之前文章里面用的一样:

= "user" User </span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> <span style="color: #0000ff;"&gt;long</span> serialVersionUID = 1L<span style="color: #000000;"&gt;; @Id @GeneratedValue </span><span style="color: #0000ff;"&gt;private</span><span style="color: #000000;"&gt; Long id; @Column(name </span>= "username"<span style="color: #000000;"&gt;) </span><span style="color: #0000ff;"&gt;private</span><span style="color: #000000;"&gt; String userName; @Column(name </span>= "password"<span style="color: #000000;"&gt;) </span><span style="color: #0000ff;"&gt;private</span><span style="color: #000000;"&gt; String passWord; </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; User() { </span><span style="color: #0000ff;"&gt;super</span><span style="color: #000000;"&gt;(); } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; User(String userName,String passWord) { </span><span style="color: #0000ff;"&gt;super</span><span style="color: #000000;"&gt;(); </span><span style="color: #0000ff;"&gt;this</span>.userName =<span style="color: #000000;"&gt; userName; </span><span style="color: #0000ff;"&gt;this</span>.passWord =<span style="color: #000000;"&gt; passWord; } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; User(Long id,String userName,String passWord) { </span><span style="color: #0000ff;"&gt;super</span><span style="color: #000000;"&gt;(); </span><span style="color: #0000ff;"&gt;this</span>.id =<span style="color: #000000;"&gt; id; </span><span style="color: #0000ff;"&gt;this</span>.userName =<span style="color: #000000;"&gt; userName; </span><span style="color: #0000ff;"&gt;this</span>.passWord =<span style="color: #000000;"&gt; passWord; } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; Long getId() { </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; id; } </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; setId(Long id) { </span><span style="color: #0000ff;"&gt;this</span>.id =<span style="color: #000000;"&gt; id; } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; String getUserName() { </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; userName; } </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; setUserName(String userName) { </span><span style="color: #0000ff;"&gt;this</span>.userName =<span style="color: #000000;"&gt; userName; } </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; String getPassWord() { </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; passWord; } </span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; setPassWord(String passWord) { </span><span style="color: #0000ff;"&gt;this</span>.passWord =<span style="color: #000000;"&gt; passWord; }

}

?6. Controller层

在user.Controller添加两个测试方法,一个写入Redis,一个从Redis读取:
"user" @Autowired </span><span style="color: #0000ff;"&gt;private</span><span style="color: #000000;"&gt; RedisService redisService; @RequestMapping(</span>"/saveUser"<span style="color: #000000;"&gt;) </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; String saveUser(Long id,String passWord) { User user </span>= <span style="color: #0000ff;"&gt;new</span><span style="color: #000000;"&gt; User(id,userName,passWord); redisService.set(id </span>+ ""<span style="color: #000000;"&gt;,user); </span><span style="color: #0000ff;"&gt;return</span> "success"<span style="color: #000000;"&gt;; } @RequestMapping(</span>"/getUserById"<span style="color: #000000;"&gt;) </span><span style="color: #0000ff;"&gt;public</span><span style="color: #000000;"&gt; User getUserById(Long id) { User res </span>= (User) redisService.get(id + ""<span style="color: #000000;"&gt;); </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; res; }

}

7. 测试

使用Postman进行测试,访问,添加了一个User。

看看Redis数据库,使用get key查看,得到一个对象:

,通过id获取User。

这是过滤器和拦截器的日志信息,可以看到没有进行MySQL数据库的操作,直接从缓存中读取,说明Redis配置生效了:

如果访问之前的接口,是有操作数据库的:

总结
以上就是Spring Boot 2.x整合Redis的全过程,和Spring Boot之前的版本在使用上有些细微的差别。
本文水平有限,或多或少有欠妥之处,还望各位大佬指正!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读