我正在使用Guice for DI开发一个使用Jersey的多租户应用程序(我也使用Dropwizard,但我认为这并不重要)。
困扰我的一件事是,我的应用程序中出现了某种tenancy_id
。我的大部分网址都是这样的:
/:tenancy_id/some_resource/do_stuff
。因此,使用tenancy_id
调用Jersey资源中的方法,并将其交给调用其他服务的服务,依此类推。对于不同的租户,这些服务的配置不同。
我设法使用@RequestScoped
TenancyIdProdiver
:
public class TenancyIdProvider {
@Inject
public TenancyIdProvider(HttpServletRequest request) {
this.request = request;
}
public TenancyId getTenancyId() {
// extract the tenancy id from the request
}
}
`
我的GuiceModule包含以下方法:
@RequestScoped
public TenancyId getTenancyId(TenancyIdProvider tenancyIdFactory) {
return tenancyIdFactory.getTenancyId();
}
public SomeTenancyService getTenancyId(TenancyId tenancyId, Configuration configuration) {
return new SomeTenancyService(configuration.getConfiguration(tenancyId));
}
所以现在我不需要担心我的服务的正确配置。所有这些都由DI容器处理,并且应用程序是租户不可知的,它不关心租户。
我的问题是:
所有这些服务和资源都是在每个请求上创建的,因为它们都具有@RequestScoped
依赖性。这根本不可行。所以我的想法是用guice创建一个自定义范围。因此,每个租户都将获得自己的对象图,其中所有资源和服务都已正确配置(但只有一次)。我按照here示例尝试了它,但是我很不确定这是否可以用Guice'自定义范围。从Jersey的角度来看,我需要在哪里输入自定义范围? ContainerRequestFilter
是正确的做法吗?
答案 0 :(得分:3)
我终于自己弄明白了。关于custom scopes的Guice页面是一个很好的起点。我需要稍微调整一下。
首先,我创建了@TenancyScoped
注释:
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@ScopeAnnotation
public @interface TenancyScoped { }
然后我使用了请求过滤器:
@PreMatching
public class TenancyScopeRequestFilter implements ContainerRequestFilter {
private final TenancyScope scope;
@Inject
public TenancyScopeRequestFilter(TenancyScope scope) {
this.scope = scope;
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Optional<TenancyId> tenancyId = getTenancyId(requestContext);
if (!tenancyId.isPresent()) {
scope.exit();
return;
}
scope.enter(tenancyId.get());
}
private Optional<TenancyId> getTenancyId(ContainerRequestContext requestContext) {
}
}
请注意@PreMatching
注释。重要的是要过滤每个请求,否则您的代码可能表现得很奇怪(范围可能设置不正确)。
这里有TenancyScope
实现:
public class TenancyScope implements Scope, Provider<TenancyId> {
private final Logger logger = LoggerFactory.getLogger(TenancyScope.class);
private final ThreadLocal<Map<TenancyId, Map<Key<?>, Object>>> tenancyIdScopedValues = new ThreadLocal<>();
private final ThreadLocal<TenancyId> tenancyId = new ThreadLocal<>();
public void enter(TenancyId tenancyId) {
logger.debug("Enter scope with tenancy id {}", tenancyId);
if (this.tenancyIdScopedValues.get() == null) {
this.tenancyIdScopedValues.set(new HashMap<>());
}
this.tenancyId.set(tenancyId);
Map<Key<?>, Object> values = new HashMap<>();
values.put(Key.get(TenancyId.class), tenancyId);
this.tenancyIdScopedValues.get().putIfAbsent(tenancyId, values);
}
public void exit() {
logger.debug("Exit scope with tenancy id {}", tenancyId.get());
this.tenancyId.set(null);
}
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
return new Provider<T>() {
public T get() {
logger.debug("Resolve object with key {}", key);
Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
@SuppressWarnings("unchecked")
T current = (T) scopedObjects.get(key);
if (current == null && !scopedObjects.containsKey(key)) {
logger.debug("First time instance with key {} is in tenancy id scope {}", key, tenancyId.get());
current = unscoped.get();
// don't remember proxies; these exist only to serve circular dependencies
if (Scopes.isCircularProxy(current)) {
return current;
}
logger.debug("Remember instance with key {} in tenancy id scope {}", key, tenancyId.get());
scopedObjects.put(key, current);
}
return current;
}
};
}
private <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key) {
Map<TenancyId, Map<Key<?>, Object>> values = this.tenancyIdScopedValues.get();
if (values == null || tenancyId.get() == null) {
throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block with id " + tenancyId.get());
}
return values.get(tenancyId.get());
}
@Override
public TenancyId get() {
if (tenancyId.get() == null) {
throw new OutOfScopeException("Cannot access tenancy id outside of a scoping block");
}
return tenancyId.get();
}
}
最后一步是在Guice模块中连接所有内容:
@Override
protected void configure() {
TenancyScope tenancyScope = new TenancyScope();
bindScope(TenancyScoped.class, tenancyScope);
bind(TenancyScope.class).toInstance(tenancyScope);
bind(TenancyId.class).toProvider(tenancyScope).in(TenancyScoped.class);
}
您现在拥有的是在每个请求之前设置的范围,Guice提供的所有实例都按照租期ID进行缓存(也可以根据每个线程进行缓存,但可以轻松更改)。基本上,每个租户ID都有一个对象图(类似于每个会话一个。)。
另请注意,TenancyScope
类同时充当Scope
和TenancyId
提供商。