概述
Redis是一款高性能key-value数据库,有丰富的数据类型string、list、hash、set、zset。
常用的应用场景
缓存、消息队列、session共享、分布式ID、分布式锁、关注/点赞、排行榜等等,我们这篇主要来讲缓存的应用
开始在SpringBoot项目中实践
- redis的安装本篇不做阐述,后续可以补充
- redis可视化工具可以自行选择安装,这里使用Redis Desktop Manager,也可以选择RedisStudio
- 本篇在之前JPA的项目基础上,我们加以改造,加入redis缓存操作
- 现在pom.xml中加入redis依赖
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2
- 在yml配置文件中加入redis配置信息
spring:
redis:
database: 0 # Redis数据库索引(默认为0)
host: localhost # Redis服务器地址
port: 6379 # Redis服务器连接端口
password: # Redis服务器连接密码(默认为空)
lettuce:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制) 默认 8
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-idle: 8 # 连接池中的最大空闲连接 默认 8
min-idle: 0 # 连接池中的最小空闲连接 默认 0
cache:
type: redis
在SpringBoot2.X,redis默认使用lettuce,基于Netty性能高于以前的jedis。
- 创建RedisConfig.java配置类
package com.zhlab.demo.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @ClassName RedisConfig
* @Description //Redis缓存配置类
* @Author singleZhang
* @Email [email protected]
* @Date 2020/11/3 0003 下午 2:15
**/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Bean
public RedisTemplate
- DAO层不变,按之前的SysAdminUserRepository.java
public interface SysAdminUserRepository extends JpaRepository, Serializable {
// 就这么简单?
// 对,就这么简单,什么都不用写,这是Spring Data JPA 默认帮我们实现了基本的数据库操作
// 如果需要扩展,可以自定义符合Spring Data JPA规则的查询方法,由框架将其自动解析为SQL
}
- Service层中加入缓存注解@CacheConfig、@Cacheable、@CachePut、@CacheEvict,SysAdminUserService.java,
package com.zhlab.demo.service;
import com.zhlab.demo.dao.SysAdminUserRepository;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.utils.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName SysAdminUserService
* @Description //SysAdminUserService
* @Author singleZhang
* @Email [email protected]
* @Date 2020/10/31 0031 上午 9:45
**/
@CacheConfig(cacheNames = "users")
@Service
public class SysAdminUserService {
@Autowired
SysAdminUserRepository sysAdminUserRepository;
@Cacheable(key="'user_'+#userId")
public SysAdminUser findUser(Long userId){
return sysAdminUserRepository.findById(userId).orElse(null);
}
@CachePut(key="'user_'+#result.adminUserId")
public SysAdminUser save(SysAdminUser user){
return sysAdminUserRepository.save(user);
}
@CacheEvict(key="'user_'+#userId")
public void deleteUser(Long userId) {
sysAdminUserRepository.findById(userId).ifPresent(sysAdminUserRepository::delete);
}
}
- 接口层,UserController.java 加入增、删、查来测试一下
package com.zhlab.demo.controller;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName UserController
* @Description //用户接口层
* @Author singleZhang
* @Email [email protected]
* @Date 2020/10/31 0031 上午 9:43
**/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
SysAdminUserService sysAdminUserService;
@ApiOperation(value = "方法名:用户信息", notes = "获取用户信息")
@GetMapping("/{userId}")
public SysAdminUser findUser(@PathVariable Long userId){
return sysAdminUserService.findUser(userId);
}
@ApiOperation(value = "方法名:新增用户", notes = "新增用户")
@PostMapping("/add")
public SysAdminUser addUser(@RequestBody SysAdminUser user){
return sysAdminUserService.save(user);
}
@ApiOperation(value = "方法名:删除用户信息", notes = "删除用户信息")
@GetMapping("/delete/{userId}")
public void deleteUser(@PathVariable Long userId){
sysAdminUserService.deleteUser(userId);
}
}
- 启动项目,打开http://localhost:8080/swagger-ui.html来调试接口
redisManager中,可以看到现在redis里现在还没数据
-
调试一下查询userId=1的用户信息
此时查看一下redis中的数据,已经新增了一条缓存数据
之后查询这用户,数据会从缓存中获取。
新增、删除调试方法类同。
9.接下来再增加另一种,通过redisTemplate来操作缓存数据,修改之前的UserController.java,
package com.zhlab.demo.controller;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* @ClassName UserController
* @Description //用户接口层
* @Author singleZhang
* @Email [email protected]
* @Date 2020/10/31 0031 上午 9:43
**/
@RestController
@RequestMapping("/user")
public class UserController {
private static final int expireTime = 30;
@Autowired
SysAdminUserService sysAdminUserService;
@Autowired
RedisTemplate redisTemplate;
@ApiOperation(value = "方法名:用户信息", notes = "获取用户信息")
@GetMapping("/{userId}")
public SysAdminUser findUser(@PathVariable Long userId){
//从缓存获取有无这个用户信息
SysAdminUser userInfo = getCacheObject("users::user_"+userId);
if(userInfo == null){
//没有,则从数据库查询
userInfo =sysAdminUserService.findUser(userId);
//设置缓存
setCacheObject("users::user_"+userId,userInfo,expireTime,TimeUnit.MINUTES);
}
return sysAdminUserService.findUser(userId);
}
@ApiOperation(value = "方法名:新增用户", notes = "新增用户")
@PostMapping("/add")
public SysAdminUser addUser(@RequestBody SysAdminUser user){
return sysAdminUserService.save(user);
}
@ApiOperation(value = "方法名:删除用户信息", notes = "删除用户信息")
@GetMapping("/delete/{userId}")
public void deleteUser(@PathVariable Long userId){
sysAdminUserService.deleteUser(userId);
}
/**
* 获取缓存
* */
private T getCacheObject(String key){
ValueOperations operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 设置缓存
* */
private ValueOperations setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {
ValueOperations operation = redisTemplate.opsForValue();
operation.set(key, value, timeout, timeUnit);
return operation;
}
}
-
继续来调试/user/{userId}这个接口
查看结果
总结
SpringBoot中使用redis缓存的方法就介绍到这儿,需要熟练掌握,因为大型项目中缓存的应用非常广泛。
项目地址
https://gitee.com/kaixinshow/springboot-note
返回【Spring Boot学习】目录