缓存现在几乎是所有中大型网站都在用的必杀技, 合理的利用缓存不仅能够提升网站访问速度, 还能大大降低数据库的压力. Redis 提供了键过期功能, 也提供了灵活的键淘汰策略, 所以, 现在 Redis 用在缓存的场合非常多.
之前有两篇博文(CentOS 安装 Redis 和 Redis 五大数据类型的常用操作), 分别介绍了 Redis 的安装和 Redis 的常用操作. 今天主要介绍介绍 springboot 整合 Redis.
v 应用场景
现在公司做的项目都偏重论坛 / 社区 / 社交类产品, 所以对 Redis 的实用场景主要集中在排行榜, 最新 / 最热内容, Redis 提供的有序集合数据类构能实现各种复杂的排行榜应用. 还有点赞, 踩, 关注 / 被关注, 共同好友等是社交网站的基本功能, 社交网站的访问量通常来说比较大, 而且传统的关系数据库类型不适合存储这种类型的数据, Redis 提供的哈希, 集合等数据结构能很方便的的实现这些功能.
还有很多应用场景, 比如分布式会话和分布式锁 (分布式锁感兴趣的可以看我之前的一篇文章《Java 分布式锁, 搞懂分布式锁实现看这篇文章就对了》) 等等, 总之越来越广泛.
v 搭建 Redis
1.1. 引入 Redis
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-Redis</artifactId>
- </dependency>
- <!--<dependency>-->
- <!--<groupId>redis.clients</groupId>-->
- <!--<artifactId>jedis</artifactId>-->
- <!--<version>2.9.0</version>-->
- <!--</dependency>-->
注意 Redis.clients 是我本地调试测试用的, 可以忽略.
1.2. 添加 RedisCacheConfig
- package com.demo.Redis;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.Redis.connection.RedisConnectionFactory;
- import org.springframework.data.Redis.core.StringRedisTemplate;
- import org.springframework.data.Redis.listener.PatternTopic;
- import org.springframework.data.Redis.listener.RedisMessageListenerContainer;
- import org.springframework.data.Redis.listener.adapter.MessageListenerAdapter;
- import java.util.concurrent.CountDownLatch;
- /**
- * Created by toutou on 2019/1/20.
- */
- @Configuration
- @EnableCaching
- public class RedisCacheConfig {
- @Bean
- RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
- MessageListenerAdapter listenerAdapter) {
- RedisMessageListenerContainer container = new RedisMessageListenerContainer();
- container.setConnectionFactory(connectionFactory);
- container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
- return container;
- }
- @Bean
- MessageListenerAdapter listenerAdapter(Receiver receiver) {
- return new MessageListenerAdapter(receiver, "receiveMessage");
- }
- @Bean
- Receiver receiver(CountDownLatch latch) {
- return new Receiver(latch);
- }
- @Bean
- CountDownLatch latch() {
- return new CountDownLatch(1);
- }
- @Bean
- StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
- return new StringRedisTemplate(connectionFactory);
- }
- public class Receiver {
- private CountDownLatch latch;
- @Autowired
- public Receiver(CountDownLatch latch) {
- this.latch = latch;
- }
- public void receiveMessage(String message) {
- latch.countDown();
- }
- }
- }
可以按需添加, 也可以按需忽略.
1.3. 添加 Redis 配置, 修改 application.properties
- # ----- Redis -------- #
- # Redis (RedisProperties)
- # Redis 数据库索引(默认为 0)
- spring.Redis.database=0
- # Redis 服务器地址
- spring.Redis.host=10.168.11.129
- # Redis 服务器连接端口
- spring.Redis.port=6379
- # Redis 服务器连接密码(默认为空)
- spring.Redis.password=
- # 连接池最大连接数(使用负值表示没有限制)
- spring.Redis.pool.max-active=8
- # 连接池最大阻塞等待时间(使用负值表示没有限制)
- spring.Redis.pool.max-wait=-1
- # 连接池中的最大空闲连接
- spring.Redis.pool.max-idle=8
- # 连接池中的最小空闲连接
- spring.Redis.pool.min-idle=0
- # 连接超时时间(毫秒)
- spring.Redis.timeout=5000
1.4. 添加 Service
- package com.demo.service;
- import com.demo.pojo.UserDetails;
- /**
- * Created by toutou on 2018/10/15.
- */
- public interface UserService {
- UserDetails getUserDetailsByUid(int uid);
- String getUserNameById(Integer uid);
- void setUserNameById(Integer uid, String userName);
- }
- UserServiceImpl
- package com.demo.service;
- import com.demo.dao.UserDetailsMapper;
- import com.demo.dao.UserPositionMapper;
- import com.demo.pojo.UserDetails;
- import com.demo.pojo.UserPosition;
- import com.google.common.base.Strings;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.Redis.core.StringRedisTemplate;
- import org.springframework.stereotype.Service;
- import java.math.BigDecimal;
- import java.util.List;
- /**
- * Created by toutou on 2018/10/15.
- */
- @Service
- public class UserServiceImpl implements UserService{
- @Autowired
- UserDetailsMapper userDetailsMapper;
- @Autowired
- UserPositionMapper userPositionMapper;
- @Autowired
- StringRedisTemplate template;
- static final String KEY_USER_INFO__NAME = "com_demo_user_info_007_%s";
- public String getUserNameById(Integer uid){
- String userName = "未知用户";
- try {
- userName = template.opsForValue().get(String.format(KEY_USER_INFO__NAME, uid));
- if (Strings.isNullOrEmpty(userName)) {
- // Redis 中没有就读数据库
- UserDetails userDetails = getUserDetailsByUid(uid);
- if (userDetails != null && !Strings.isNullOrEmpty(userDetails.getCity())) {
- userName = userDetails.getCity();
- }
- }
- }catch(Exception e){
- System.out.println(e.toString());
- }
- return userName;
- }
- public void setUserNameById(Integer uid, String userName){
- template.opsForValue().set(String.format(KEY_USER_INFO__NAME, uid), userName);
- }
- public UserDetails getUserDetailsByUid(int uid){
- return userDetailsMapper.getUserDetailsByUid(uid);
- }
- }
1.5. 添加 RedisController
- package com.demo.controller;
- import com.demo.service.UserService;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.Web.bind.annotation.RestController;
- import Redis.clients.jedis.Jedis;
- /**
- * Created by toutou on 2019/1/20.
- */
- @RestController
- @Slf4j
- public class RedisController {
- @Autowired
- UserService userService;
- @RequestMapping(value = "/getusernamebyid")
- public String getUserNameById(Integer uid)
- {
- return userService.getUserNameById(uid);
- }
- @RequestMapping(value = "/setusernamebyid")
- public String setUserNameById(Integer uid, String uname)
- {
- userService.setUserNameById(uid, uname);
- return "设置成功";
- }
- @RequestMapping(value = "/jedistest")
- public String jedisTest(){
- // 创建一个 jedis 对象
- Jedis jedis = new Jedis("ip", 6379);
- // 直接调用 jedis 对象的方法, 方法名称和 Redis 的命令一致
- jedis.set("key1", "test01");
- String key1 = jedis.get("key1");
- System.out.println(key1 + " " + key1);
- // 关闭 jedis
- jedis.close();
- return key1;
- }
- }
注意 jedisTest 是我本地调试测试用的, 可以忽略.
vRedis 测试效果
v 源码地址
作 者: 请叫我头头哥
来源: https://www.cnblogs.com/toutou/p/spring_boot_redis.html