引入redis
pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
yml文件
spring:
redis:
host: 127.0.0.1
port: 6379
# 请尽量吧redis的密码复杂化,要不然服务器容易被挖矿
password: *****
database: 10
创建redisConfig
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.javaweb.common.redis.utils.JsonUtils;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis缓存配置类
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@SuppressWarnings(value = {"unchecked", "rawtypes", "deprecation"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
JsonUtils serializer = new JsonUtils(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
// value序列化方式采用 jackson
template.setValueSerializer(serializer);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
创建注入config
import com.alibaba.fastjson.JSON;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author king
* 自动添加redis
*/
@Configuration
public class TransfuseConfig {
@Bean("getKeyGenerator")
public KeyGenerator getKeyGenerator(){
return (o, method, objects) -> {
//编辑redis的查询键
String name = o.getClass().getSimpleName();
List list= Arrays.asList(objects);
list.forEach(System.out::println);
Object obj1 = list.get(0);
Map<String, Object> map = JSON.parseObject(JSON.toJSONString(obj1), HashMap.class);
Integer current = (Integer) map.get("page");
Integer size = (Integer) map.get("limit");
return name+current+size;
};
}
}
service添加注解
@Override
//他就是自动注入redis的注解方式
@Cacheable(value="query", keyGenerator = "getKeyGenerator")
public Page<GoodsDtoVo> query(GoodsQuery goodsQuery) {
// 逻辑自己写
return new ArrerList;
}
最后 上次用的忘了记录 ,随手记下来来了,看不懂留言 ,或者直接复制下来试一试,也可以继续度娘