SpringBoot中使用Redis

在SpringBoot中使用Redis,思路如下:

查询时先查Redis缓存,如果缓存中存在信息,就直接从缓存中获取。

如果缓存中没有相关信息,就去数据库中查找,查完顺便将信息存放进缓存里,以便下一次查询。

另外,更新或者删除数据库数据时,记得删除相关的缓存。

在SpringBoot中使用Redis的步骤如下:

1.首先,添加依赖包:

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.2.RELEASE</version>
 </dependency>

2.在application.properties中添加Redis配置:

## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=127.0.0.1
## 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=0

3.对象序列化后才能存储到Redis。我们需要将对象类实现序列化接口 RedisSerializer,并生成serialVersionUID。

如果不实现RedisSerializer接口,会报异常:

IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type

serialVersionUID在eclipse和Intellij Idea中都可以自动生成。详情百度查找。

public class User implements Serializable {
    private static final long serialVersionUID = 4798316249512579846L;

    private String uid;
    
    private String userName;
   
    private String name;
    
    private String password;
   
 //省略其他的构造方法、getter()、setter()等
     
}

 4.在服务层进行缓存操作,如下所示:

@Service
public class UserServiceImpl implements UserSerevice {
 
    @Autowired
    private UserDao userDao;
  
//redisTemplate在注入时,无需声明泛型
    @Autowired
    private RedisTemplate redisTemplate;
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Override public User showUsers(String uid){ //从缓存中获取信息 ValueOperations<String,User> valueOperations=redisTemplate.opsForValue(); //判断缓存是否有记录,如果有记录就直接从缓存中获取信息 boolean hasKey=redisTemplate.hasKey(uid); if(hasKey) { User user= valueOperations.get(uid); logger.debug("====================>从缓存中获取了用户id为"+uid+"的用户信息."); return user; } User user =userDao.selectByPrimaryKey(uid); //如果缓存中不存在信息,在查询过后,就将信息插入缓存中 if(user!=null) { valueOperations.set(uid,user); logger.debug("====================>将用户id为"+uid+"的用户信息插入缓存中."); } return user; } }
原文地址:https://www.cnblogs.com/expiator/p/9443227.html