Skip to content
On this page

缓存中间件集成组件

基于 Caffeine + Redis 实现的多级缓存组件

如何使用

1. 引入依赖

xml
<dependency>
    <groupId>com.chinapost.mids</groupId>
    <artifactId>cpms-cache-spring-boot-starter</artifactId>
    <version>1.0.0-RELEASE</version>
</dependency>

2. 开启缓存支持

java
@EnableCaching
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

3. 目标方法声明 Spring Cache 注解

java
@Cacheable(key = "'cache_user_id_' + #id", value = "userIdCache")
@GetMapping("/getUserById")
public UserVO getUserById(Long id) {
        UserVO vo = new UserVO();
        vo.setId(id);
        vo.setName("张三");
        return vo;
}

@PostMapping("/update")
@CachePut(key = "'cache_user_id_' + #userVO.id", value = "userIdCache")
public UserVO update(@RequestBody UserVO userVO) {
        return userVO;
}

@DeleteMapping("/delete")
@CacheEvict(key = "'cache_user_id_' + #id", value = "userIdCache")
public void delete(Long id) {
    
}

4. 配置示例

yaml
spring:
  redis:
    database: 0
#    password: 123456
    timeout: 3000
    #sentinel/cluster/single
    mode: single
    # 连接池配置
    pool:
      max-idle: 16
      min-idle: 8
      max-active: 8
      max-wait: 3000
      conn-timeout: 3000
      so-timeout: 3000
      size: 10
    single:
      address: localhost:6379
  # 两级缓存配置  
  cache:
    multi:
      caffeine:
        expireAfterAccess: 5000
      redis:
        defaultExpiration: 60000
    # spring cache配置
    cache-names: userIdCache,userNameCache

性能比较

为保证性能 redis 在 127.0.0.1 环路安装

  • OS: macOS Mojave
  • CPU: 2.3 GHz Intel Core i5
  • RAM: 8 GB 2133 MHz LPDDR3
  • JVM: corretto_11.jdk
BenchmarkModeCntScoreUnits
多级实现thrpt22716.074ops/s
默认 redisthrpt21373.476ops/s