我有一个服务类,该服务类需要调用与其他服务不同的api。 但是每个API都有一些限制,所以我使用Guava的Ratelimiter来强制执行操作限制
@Singleton
public class A {
private final RateLimiter apiCallX;
private final int timeoutInSecondsForAPIX;
private final RateLimiter apiCallY;
private final int timeoutInSecondsForAPIY;
@Inject
public A ( @Named("apiCallXRateLimiter") apiCallX,
@Named("apiCallXRateLimiter") apiCallY,
@Named("apiCallXRateLimiter") apiCallZ,
){
this.apiCallX = apiCallX;
...
}
public ResponseX callAPIX (){
...
}
public ResponseY callAPIY (){
...
}
private modelTransformer(){ //each for request and response and for each call.
...
}
}
我正在考虑使用继承来避免群集此类中的所有操作调用。 在这种情况下,我还可以使用哪些其他设计模式?
答案 0 :(得分:0)
您可以使用AOP框架或其背后的模式,例如代理模式:
interface ServiceX {
ResponseX execute();
}
@Alternative
@Named("serviceX")
class ServiceXImpl implements ServiceX {
@Override
public ResponseX execute() {
//call to X API
return null;
}
}
@Default
class ServiceXProxyImpl implements ServiceX {
@Inject
@Named("serviceXLimiter")
RateLimiter rateLimiter;
@Inject
@Named("serviceX")
ServiceX serviceX;
@Override
public ResponseX execute() {
rateLimiter.acquire();
return serviceX.execute();
}
}
现在无论您在何处声明@Inject ServiceX serviceX
,DI框架都应使用速率限制器注入实现