Solon v2.8.6

solon.cache.redisson

</> markdown
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.cache.redisson</artifactId>
</dependency>

1、描述

数据扩展插件,为 Solon Data 提供基于 redisson 的框架适配。主要实现 CacheService 接口。

2、配置示例

使用简化配置(对应 RedissonClientSupplier 或 RedissonCacheService 或 CacheServiceSupplier 注入)

#完整配置示例
demo.cache1:
  driverType: "redis" #驱动类型
  keyHeader: "demo" #默认为 ${solon.app.name} ,可不配置
  defSeconds: 30 #默认为 30,可不配置
  server: "localhost:6379"
  db: 0 #默认为 0,可不配置
  password: ""
  idleConnectionTimeout: 10000
  connectTimeout: 10000


#简配示例
demo.cache2:
  server: "localhost:6379"

使用原始风格配置(对应 RedissonClientOriginalSupplier 注入)

redis.ds1:
  file: "classpath:redisson.yml"

redis.ds2:
  config: |
    singleServerConfig:
      password: "123456"
      address: "redis://localhost:6379"
      database: 0

3、序列化选择

solon.data 自带了两个缓存时的序列化选择

序列化方案类型(Model)泛型(List<Model>泛型2(T, List<T>
JavabinSerializer.instance支持支持支持
JsonSerializer.instance支持支持(1)/
JsonSerializer.typedInstance支持支持支持
  • 支持(1),需要 v2.8.5 后支持

4、应用示例

//配置缓存服务
@Configuration
public class Config {
    @Bean(name = "cache1", typed = true) //typed 表示可类型注入 //即默认
    public CacheService cache1(@Inject("${demo.cache1}") RedissonCacheService cache){
        return cache;
    }
    
    //通过 CacheServiceSupplier ,可根据 driverType 自动构建缓存服务
    //@Bean(name = "cache1s")
    public CacheService cache1s(@Inject("${demo.cache1}") CacheServiceSupplier supplier){
        return supplier.get();
    }
    
    //自己建构客户端  //虽然更自由,但不推荐
    //@Bean(name = "cache2s")
    public CacheService cache2s(@Inject("${demo.cache2}") Properties props){
        RedissonClient client = new RedissonClient(...);    
        return new RedissonCacheService(client, 30, "demo");
    }
    
    //通过 RedissonClientOriginalSupplier(使用原始风格配置)构建客户端
    //@Bean
    public RedissonClient redis3(@Inject("${demo.redis3}") RedissonClientOriginalSupplier supplier){
        return supplier.get();
    }
}

//应用
@Controller
public class DemoController {
    //使用默认缓存服务。如果有缓存,直接返回缓存;如果没有,执行函数,缓存结果,并返回
    @Cache
    public String hello(String name) {
        return String.format("Hello {0}!", name);
    }
    
    //提醒:如果是实体,实体类要加 toString() 函数!!!
    @Cache
    public String hello2(UserModel user) { 
        return String.format("Hello {0}!", user.name);
    }
}

4、自定义序列化示例

@Configuration
public class Config {
    @Bean
    public CacheService cache1(@Inject("${demo.cache1}") RedissonCacheService cache){
        //设置自定义的序列化接口(借了内置的对象)
        return cache.serializer(JavabinSerializer.instance);  //或 JsonSerializer.instance //或 自己实现
    }
}

//提示:泛序列化存储,在反序列化时是不知道目标类型的,序列化时须附带类型信息

5、Key 使用明文

@Configuration
public class Config {
    @Bean
    public CacheService cache1(@Inject("${demo.cache1}") RedissonCacheService cache){
        cache.enableMd5Key(false);
        return cache;
    }
}