目的:为了spring上下文添加读写分离的接口,可以在启动后自动注入redis只读接口或可读写接口
1. 定义一个相关的functional interface - 在spring boot的启动类里面要用到(@EnableDynamicKeyValueServiceCreation)
@Retention(value = RetentionPolicy.RUNTIME)
@Import(KeyValueServiceRegister.class)
public @interface EnableDynamicKeyValueServiceCreation {
}
2. 定义只读接口和可读写接口
public interface KeyValueReadService { String get(String key); ...}
public interface KeyValueReadWriteService extends KeyValueReadService { void set(String key, String value); ..}
3. 实现类
public class RedisConfigInfo {
private String hostName;
private int port;
private String password;
private JedisPoolConfig poolConfig;
}
public abstract class AbstractRedisOperation {
private final JedisPool jedisPool;
public AbstractRedisOperation (RedisConfigInfo info) { jedisPool = ...;}
}
public class RedisReadServiceImpl extends AbstractRedisOperation implements KeyValueReadService {
public RedisReadServiceImpl(RedisConfigInfo temp) {
super(temp);
}
@Override
public String get(String key) {
return stringValueOps.get(key);
}
}
4. 通过spring去获取redis的配置信息
@Component
public class KeyValueServi