引入依赖
<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>
配置
spring:
cache:
type: redis
redis:
host: localhost
port: 6379
username:
password:
database: 1
配置类
package com.qiangesoft.cache.config;
import org.springframework.cache.CacheManager;
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.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@EnableCaching
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport {
private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
private static final GenericJackson2JsonRedisSerializer JACKSON__SERIALIZER = new GenericJackson2JsonRedisSerializer();
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(3))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(STRING_SERIALIZER))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(JACKSON__SERIALIZER));
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(cacheConfiguration)
.build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(STRING_SERIALIZER);
redisTemplate.setValueSerializer(JACKSON__SERIALIZER);
redisTemplate.setHashKeySerializer(STRING_SERIALIZER);
redisTemplate.setHashValueSerializer(JACKSON__SERIALIZER);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
服务类
package com.qiangesoft.cache.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Service
public class UserInfoService {
private final Map<Long, UserInfo> userInfoMap = new ConcurrentHashMap<>();
private final String CACHE_KEY = "user";
@CachePut(cacheNames = CACHE_KEY, key = "#userInfo.id")
public UserInfo add(UserInfo userInfo) {
log.info("UserInfoService.add() execute db !");
userInfoMap.put(userInfo.getId(), userInfo);
return userInfo;
}
@CacheEvict(cacheNames = CACHE_KEY, key = "#id")
public void removeById(Long id) {
log.info("UserInfoService.removeById() execute db !");
userInfoMap.remove(id);
}
@CacheEvict(cacheNames = CACHE_KEY, allEntries = true)
public void remove() {
log.info("UserInfoService.remove() execute db !");
userInfoMap.clear();
}
@CacheEvict(cacheNames = CACHE_KEY, key = "#userInfo.id")
public void updateById(UserInfo userInfo) {
log.info("UserInfoService.updateById() execute db !");
userInfoMap.put(userInfo.getId(), userInfo);
}
@Cacheable(cacheNames = CACHE_KEY + ":list")
public List<UserInfo> listAll() {
log.info("UserInfoService.listAll() execute db !");
return new ArrayList<>(userInfoMap.values());
}
@Cacheable(cacheNames = CACHE_KEY, key = "#id", unless = "#result == null")
public UserInfo getById(Long id) {
log.info("UserInfoService.getById() execute db !");
UserInfo userInfo = userInfoMap.get(id);
return userInfo;
}
}
测试
package com.qiangesoft.cache.controller;
import com.qiangesoft.cache.service.UserInfo;
import com.qiangesoft.cache.service.UserInfoService;
import com.qiangesoft.cache.utils.CacheManagerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping("/user")
@RestController
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
@Autowired
private CacheManagerUtil cacheManagerUtil;
@PostMapping
public void add(@RequestBody UserInfo userInfo) {
userInfoService.add(userInfo);
}
@DeleteMapping("/{id}")
public void removeById(@PathVariable Long id) {
userInfoService.removeById(id);
}
@DeleteMapping("/all")
public void remove() {
userInfoService.remove();
}
@PutMapping
public void updateById(@RequestBody UserInfo userInfo) {
userInfoService.updateById(userInfo);
}
@GetMapping
public List<UserInfo> listAll() {
return userInfoService.listAll();
}
@GetMapping("/{id}")
public UserInfo getById(@PathVariable Long id) {
return userInfoService.getById(id);
}
@GetMapping("/current")
public Object current(String id) {
Object user = cacheManagerUtil.getCache("user", id);
return user;
}
}