SpringBoot & SpringCache & Redis 整合
单体项目,缓存技术
步骤
1.导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/>
</parent>
<groupId>com.demo</groupId>
<artifactId>SpringCacheRedisDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<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>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.编写redisCache配置类
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer ());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer ());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
}
}
3.编写对应SpringCache注解
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
private static final HashMap<String, Product> stringProductHashMap = new HashMap<> ();
static {
stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000001L,"手机"));
stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000002L,"笔记本"));
stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000003L,"电脑"));
stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000003L,"飞机"));
}
public static void main(String[] args) {
show();
}
private static void show() {
for (String s : stringProductHashMap.keySet ()) {
System.out.println (stringProductHashMap.get (s));
}
}
@Cacheable(value = "product", key = "#id")
@Override
public Product select(Long id) {
System.out.println ("我被执行了");
log.info("查询【id】= {}", id);
return stringProductHashMap.get(id);
}
@CachePut(value = "product", key = "#product.id")
@Override
public Product saveOrUpdate(Product product) {
System.out.println ("我被执行了");
stringProductHashMap.put(product.getId().toString (), product);
log.info("保存【product】= {}", product);
return product;
}
@CacheEvict(value = "product", key = "#id")
@Override
public void delete(Long id) {
System.out.println ("我被执行了");
stringProductHashMap.remove(id);
log.info("删除【id】= {}", id);
}
}
4.测试
@Slf4j
@SpringBootTest
@Rollback(value=true)
@RunWith(SpringRunner.class)
public class RedisCacheDemoTest {
@Autowired
ProductServiceImpl productService;
@Test void del(){
for (int i = 0; i < 5; i++) {
System.out.println (i);
productService.delete (1L);
}
}
@Test
public void select(){
for (int i = 0; i < 5; i++) {
System.out.println (i);
productService.select (1L);
}
}
@Test
public void saveOrUpdate() {
for (int i = 0; i < 5; i++) {
System.out.println (i);
productService.saveOrUpdate (new Product (1L,"admin" ));
}
}
}
5.结果
- 开启缓存
- 关闭缓存
其他操作都相似
可以使用AOP以及自定义注解实现个性化缓存
知识点
@Cacheable:触发缓存写入。
@CacheEvict:触发缓存清除。
@CachePut:更新缓存(不会影响到方法的运行)。
@Caching:重新组合要应用于方法的多个缓存操作。
@CacheConfig:设置类级别上共享的一些常见缓存设置。