spring boot redis cache 缓存学习
- 自定义redis key前缀
- 自定义redis key
- 自定义全局key过期时间
- 针对单个key自定义过期时间
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
自定义redis key前缀
package com.km.config;
import org.springframework.data.redis.cache.RedisCachePrefix;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* <p>redis前缀配置,有时候多个工程共用一个db需要区分</p>
* Created by zhezhiyong@163.com on 2017/9/22.
*/
public class RedisPrefix implements RedisCachePrefix {
private final RedisSerializer serializer;
private final String delimiter;
public RedisPrefix() {
this(":");
}
public RedisPrefix(String delimiter) {
this.serializer = new StringRedisSerializer();
this.delimiter = delimiter;
}
@Override
public byte[] prefix(String cacheName) {
return this.serializer.serialize(this.delimiter != null ? this.delimiter.concat(":").concat(cacheName).concat(":") : cacheName.concat(":"));
}
}
自定义redis key
@Override
@Cacheable(value = "user", key = "'user'.concat(#id.toString())")
public User findUserById(Long id) {
log.info("findUserById query from db, id: {}", id);
return userMap.get(id);
}
@Override
@CachePut(value = "user", key = "'user'.concat(#user.id.toString())")
public User update(User user) {
log.info("update db, user: {}", user.toString());
userMap.put(user.getId(), user);
return user;
}
@Override
@CacheEvict(value = "user", key = "'user'.concat(#id.toString())")
public void remove(Long id) {
log.info("remove from db, id: {}", id);
userMap.remove(id);
}
自定义key过期时间
package com.km.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCachePrefix;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* <p>redis缓存配置</p>
* Created by zhezhiyong@163.com on 2017/9/21.
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public KeyGenerator KeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager manager = new RedisCacheManager(redisTemplate);
manager.setUsePrefix(true);
RedisCachePrefix cachePrefix = new RedisPrefix("prefix");
manager.setCachePrefix(cachePrefix);
// 整体缓存过期时间
manager.setDefaultExpiration(3600L);
// 设置缓存过期时间。key和缓存过期时间,单位秒
Map<String, Long> expiresMap = new HashMap<>();
expiresMap.put("user", 1000L);
manager.setExpires(expiresMap);
return manager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
配置yml
server:
port: 8080
spring:
cache:
type: redis
redis:
host: 192.168.97.57 # server host
port: 6379 # connection port
pool.max-idle: 8 # pool settings ...
pool.min-idle: 1
pool.max-active: 8
pool.max-wait: -1
database: 0
配置启动
package com.km;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class SpringBootRedisCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRedisCacheApplication.class, args);
}
}
示例
点击下载源码,如果对你有帮助请赏赐一个star