抽象类:
import com.citi.risk.core.configuration.api.Configuration;
public abstract class AbstractXXXSwitcher<I> {
@Autowised
private Configuration configuration;
private I executor_1;
private I executor_2;
protected AbstractClimateRiskSwitcher(I executor_1, I executor_2) {
this.executor_1 = executor_1;
this.executor_2 = executor_2;
}
protected <R> R read(Function<I, R> function) {
R data;
int mode = getAccessMode();
if (mode == 0) {
data = function.apply(executor_1);
} else {
data = function.apply(executor_2);
}
return data;
}
protected void readAndSet(Consumer<I> consumer) {
int mode = getAccessMode();
if (mode == 0) {
consumer.accept(executor_1);
} else {
consumer.accept(executor_2);
}
}
protected void write(Consumer<I> consumer) {
int mode = getAccessMode();
try {
consumer.accept(executor_2);
} catch (Exception e) {
LOGGER.error("Exception thrown in write of MS", e);
}
if (mode == 0 || mode == 1) {
consumer.accept(executor_1);
}
}
protected <R> R writeAndGet(Function<I, R> function) {
R data;
int mode = getAccessMode();
if (mode == 0) {
try {
function.apply(executor_2);
} catch (Exception e) {
LOGGER.error("Exception thrown in writeAndGet of MS", e);
}
data = function.apply(executor_1);
} else if (mode == 1) {
data = function.apply(executor_2);
function.apply(executor_1);
} else {
data = function.apply(executor_2);
}
return data;
}
/**
*
* 0: write to both executor_1 and executor_2, read from executor_1.
* 1: write to both executor_1 and executor_2, read from executor_2.
* 2: write to executor_2 only, read from executor_2.
*
* @return access mode.
*/
private int getAccessMode() {
return Integer.parseInt(configuration.getPrefixProperties("PREFIX").getProperty("PROPERTY", "0"));
}
}
最后获取开关的值可以配置在central config里,通过更改这个值就可以实现对双写的控制
configuration.getPrefixProperties("PREFIX").getProperty("PROPERTY", "0")
具体用法:
@Singleton
public class XXXHandlerProxy extends AbstractXXXSwitcher<XXXHandler> implements XXXHandler {
@Inject
public XXXHandlerProxy(Handler1 handler1 , Handler2 handler2) {
super(handler1 , handler2);
}
@Override
public Object foo(Object o) {
return read(handler -> handler.method(o));
}
}
XXXHandler 接口:
public interface XXXHandler {
Object foo(Object o);
}