Solon v3.0.3

七、缓存分区设计

</> markdown

在日常开发中,总会有想法给缓存做分区归划。比如订单类的放一块儿,用户类的放一块儿

1、添加两个缓存配置

下面这个设计是(仅作参考),用户缓存放 db0 区,且缓存键以 "user:" 开头。订单缓存放 db1 区,且缓存键以 "order:" 开头。

demo.cache.user:
  keyHeader: "user" 
  server: "localhost:6379"
  db: 0

demo.cache.order:
  keyHeader: "order" 
  server: "localhost:6379"
  db: 1

2、构建缓存服务

@Configuration
public class Config {
    @Bean("cache_user")
    public CacheService cache_user(@Inject("${demo.cache.user}") RedisCacheService cache){
        return cache.enableMd5key(false); //默认不开启 md5(key)
    }

    @Bean("cache_order")
    public CacheService cache_order(@Inject("${demo.cache.order}") RedisCacheService cache){
        return cache.enableMd5key(false);
    }
}

3、分区使用缓存服务

@Component
public class DemoOrderService {
    @Cache(service="cache_order")
    public String hello(String name) {
        return String.format("Hello {0}!", name);
    }
}

@Component
public class DemoUserService {
    @Cache(service="cache_user")
    public String hello(String name) {
        return String.format("Hello {0}!", name);
    }
}