更新时间:2024-10-23 GMT+08:00
自定义DcsConnection
使用场景:使用RedisTemplate命令时,DcsConnection中的接口没有覆盖到的情况,可以自定义扩展DcsConnection。
- 自定义DcsConnection。
- type选择为normal时使用。
import com.huawei.devspore.mas.Redis.core.MultiZoneClient; import com.huawei.devspore.mas.Redis.spring.boot.cache.DcsConnection; public class CusConnection extends DcsConnection { public CusConnection(MultiZoneClient client) { super(client); } // template中不支持但dcs中有的命令,可通过重写相应方法实现 @Override public Long hLen(byte[] key) { return client.hlen(key); } }
- type选择为cluster时使用。
1 2 3 4 5 6 7 8 9 10 11 12 13
import com.huawei.devspore.mas.Redis.core.MultiZoneClient; import com.huawei.devspore.mas.Redis.spring.boot.cache.DcsClusterConnection; public class CusClusterConnection extends DcsClusterConnection { public CusClusterConnection(MultiZoneClient client) { super(client); } // template中不支持但dcs中有的命令,可通过重写相应方法实现 @Override public Long hLen(byte[] key) { return client.hlen(key); } }
- type选择为normal时使用。
- 自定义RedisConnectionFactory。
import com.huawei.devspore.mas.Redis.core.MultiZoneClient; import org.springframework.dao.DataAccessException; import org.springframework.data.Redis.connection.RedisClusterConnection; import org.springframework.data.Redis.connection.RedisConnection; import org.springframework.data.Redis.connection.RedisConnectionFactory; import org.springframework.data.Redis.connection.RedisSentinelConnection; public class CusConnectionFactory implements RedisConnectionFactory { private final MultiZoneClient client; public CusConnectionFactory(MultiZoneClient client) { this.client = client; } @Override public RedisConnection getConnection() { // 单机或主从模式使用 return new CusConnection(client); } @Override public RedisClusterConnection getClusterConnection() { // 集群模式使用 return new CusClusterConnection(client); } @Override public boolean getConvertPipelineAndTxResults() { return false; } @Override public RedisSentinelConnection getSentinelConnection() { return null; } @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { return null; } }
- 配置类中指定自定义的RedisConnectionFactory。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
@Configuration public class TemplateConfig { @Bean public CusConnectionFactory dcsConnectionFactory(MultiZoneClient client) { return new CusConnectionFactory(client); } @Bean @Primary @ConditionalOnSingleCandidate(CusConnectionFactory.class) public RedisTemplate<Object, Object> RedisTemplate(CusConnectionFactory RedisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(RedisConnectionFactory); return template; } }
父主题: 客户各场景替换方案