1.添加依赖
<!--spring-缓存依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--方式二还需添加的依赖-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.2</version>
</dependency>
2.配置Cache
(1).配置1(在Application启动类添加@EnableCaching注解)
@SpringBootApplication
@MapperScan("com.xxxx.dao")
@EnableCaching
public class AxxxxApplication {
public static void main(String[] args) {
SpringApplication.run(AxxxxApplication.class, args);
}
}
(2).配置2(配置cache的缓存类型,这里主要介绍的本地缓存)
//方式一:ConcurrentMapCache (不好设置过期时间)
@Configuration
public class SpringCachingConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
Set<ConcurrentMapCache> mapCaches=new HashSet<>();
//配置cache类型与目录
mapCaches.add(new ConcurrentMapCache("cacheNames1"));
mapCaches.add(new ConcurrentMapCache("cacheNames2"));
mapCaches.add(new ConcurrentMapCache("cacheNames3"));
mapCaches.add(new ConcurrentMapCache("cacheNames4"));
cacheManager.setCaches(mapCaches);
cacheManager.afterPropertiesSet();
return cacheManager;
}
}
//方式二:CaffeineCache (可设置过期时间)
@Configuration
public class SpringCachingConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
List<CaffeineCache> caffeineCaches = new ArrayList<>();
//SysConstants.CACHE_NAMES=new ArrayList(
//Arrays.asList("cacheNames1","cacheNames2","cacheNames3","cacheNames4")
//);
for (String cacheName: SysConstants.CACHE_NAMES) {
caffeineCaches.add(new CaffeineCache(cacheName,
Caffeine.newBuilder()
.initialCapacity(50)
.maximumSize(30000)//最大存储数量
.expireAfterWrite(2, TimeUnit.HOURS)//过期时间2 小时
.build()));
}
cacheManager.setCaches(caffeineCaches);
return cacheManager;
}
}
//方式三。。。。还可以配置redis以及其他的方式,这里主要介绍以上两种方式
3.使用
//控制器1
@RestController
@RequestMapping("/path1")
@Cacheable(cacheNames = "cacheNames1" ,key="#root.methodName+#a0" )
public class Controller1 {
}
//控制器2
@RestController
@RequestMapping("/path1")
@Cacheable(cacheNames = "cacheNames2" ,key="#root.methodName+#a0" )
public class Controller1 {
}
//控制器3
@RestController
@RequestMapping("/path1")
@Cacheable(cacheNames = "cacheNames3" ,key="#root.methodName+#a0" )
public class Controller1 {
}
//控制器4
@RestController
@RequestMapping("/path1")
@Cacheable(cacheNames = "cacheNames4" ,key="#root.methodName+#a0" )
public class Controller1 {
}
|