引入redis依赖
<!-- redis依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application.yml配置redis相关的配置
spring:
#Redis配置
redis:
#Redis服务器地址
host: 127.0.0.1
#Redis服务器端口号
port: 6379
#Redis数据库索引(默认为0)
database: 0
jedis:
pool:
#连接池最大连接数(使用负值表示没有限制)
max-active: 50
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 3000
#连接池中的最大空闲连接
max-idle: 20
#连接池中的最小空闲连接
min-idle: 2
#连接超时时间(毫秒)
timeout: 5000
在springboot启动类中配置**@EnableCaching**注解
@EnableCaching:是spring framework中的注解驱动的缓存管理功能
在方法中添加**@Cacheable**注解
@Cacheable:标注在方法上表示改方法支持缓存(个人理解)
(在使用@Cacheable需要在实体类中实现Serializable接口,实现序列化)
导入springframework包下的Cacheable
org.springframework.cache.annotation.Cacheable
创建RedisConfig工具类,使redis缓存的数据为json格式
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* Redis缓存管理器
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//设置CacheManager的值序列化方式为json序列化
RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
.fromSerializer(jsonSerializer);
RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(pair);
//设置默认超过期时间是30秒
defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
//初始化RedisCacheManager
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
}
需要把vo返回的对象也要实现序列化
Function<String, List<Student>> fun = (msg) -> {
return studentService.selectStudentAll(msg);
};
List<Student> list = fun.apply(name);
Student对象实现Serializable序列化
(省略get,set方法)
public class Student implements Serializable {
private String id;
private String name;
private Integer age;
private String sex;
}
配置好redis序列化工具后需要在springboot启动类中添加 @EnableCaching
来打开缓存
@SpringBootApplication
@EnableCaching
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
在方法中使用@Cacheable(value = “index”)这个value一定要添加,相当于redis缓存中key
@Cacheable(value = "index")
@PostMapping("/index")
@ApiOperation(value = "根据姓名查询学生信息 - 模糊查询", notes = "查询学生姓名", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiImplicitParams({
@ApiImplicitParam(name = "name", dataType = "String", required = true, value = "学生姓名", paramType = "query")
})
public List<Student> index(String name){
Function<String, List<Student>> fun = (msg) -> {
return studentService.selectStudentAll(msg);
};
List<Student> list = fun.apply(name);
//输出log4j日志
logger.info("index被执行");
return list;
}
删除redis已缓存数据
创建redisUtil工具类
import redis.clients.jedis.Jedis;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
/**
* Redis缓存处理
*/
public class RedisUtil {
//log4j日志
private static Logger logger = Logger.getLogger(String.valueOf(RedisUtil.class));
/**
* 根据Redis的key删除已缓存的数据
* @param str
* @return
*/
public Boolean delRedisKey(String str) {
Boolean result = false;
//连接redis库
Jedis jedis = cli_single("127.0.0.1", 6379);
//获取到redis库里所有的key
Set<String> set = jedis.keys("*");
if (set.size() != 0){
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()){
String key = iterator.next();
if (key.contains(str)){
if (jedis.del(key) == 1){
logger.info("删除Key中含有"+ key +"的成功");
result = true;
} else {
logger.info("删除失败");
}
}
}
}
return result;
}
/**
* 删除Redis已缓存的所有key
* @return
*/
public Boolean delRedis(){
Boolean result = true;
Jedis jedis = cli_single("127.0.0.1", 6379);
//获取到redis库里所有的key
Set<String> set = jedis.keys("*");
if (set.size() != 0){
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()){
String key = iterator.next();
jedis.del(key);
}
}
return result;
}
/**
* 单个连接
*
* @param host
* @param port
* @return
*/
public static Jedis cli_single (String host,int port){
try {
return new Jedis(host, port);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
在controller中需要修改数据库中的数据的方法中条用
/**
* 删除redis缓存
* @param str
*/
private void redisUtil(String str){
RedisUtil redisUtil = new RedisUtil();
redisUtil.delRedisKey(str);
}
示例:
public String delete(String id){
String result = null;
Integer integer = studentService.deleteStudentById(id);
if (integer == 1){
result = "SUCCESS";
**this.redisUtil("index");**
} else {
result = "FAILURE";
}
return result;
}
944

被折叠的 条评论
为什么被折叠?



