[英]Singleton instance per region
I have a Dynamo DB DAO class, which takes the region like us-east-1, us-east-2 etc., to instantiate the object and interacts with DDB. 我有一个Dynamo DB DAO类,该类采用us-east-1,us-east-2等区域来实例化对象并与DDB进行交互。 Now I am processing a stream of messages, which contains this region value along with other payload to be written to DDB. 现在,我正在处理消息流,其中包含此区域值以及其他要写入DDB的有效负载。 I want to ensure a single instance of DAO object is created per region. 我想确保每个区域都创建一个DAO对象实例。 Currently I have created a map holding all the Dao instances per region and using it for each request to achieve this. 目前,我已经创建了一个地图,其中包含每个区域的所有Dao实例,并将其用于每个请求以实现此目的。
Sample code that I'm using looks like below. 我正在使用的示例代码如下所示。
public class DDBDao {
private DynamoDBMapper dynamoDBMapper;
public DDBDao(final string region) {
AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder.standard()
.withRegion(Regions.fromName(region))
.build();
this.dynamoDBMapper = new DynamoDBMapper(dynamoDBClient);
}
public save(..) {
dynamoDBMapper.save(...)
}
....
}
@Singleton
public class DaoContainer {
Map<String, DDBDao> daoContainer = new HashMap<>();
DaoContainer() {
daoContainer.put("us-east-1", new DDBDao("us-east-1"));
daoContainer.put("us-east-2", new DDBDao("us-east-2"));
.....
}
}
I create a instance of DaoContainer and get the DDBDao for the given region to interact with DynamoDB. 我创建了DaoContainer的实例,并获取给定区域的DDBDao与DynamoDB进行交互。 What is the best way to create singleton instances of DDBDao per region? 在每个区域中创建DDBDao的单例实例的最佳方法是什么?
I would suggest implementing custom Region scoped bean, this works exactly same as request/ session scope beans except spring will maintain bean object per Region. 我建议实现自定义Region范围的bean,这与请求/会话范围的bean完全一样,只是spring将为每个Region维护bean对象。
org.springframework.beans.factory.config.Scope
is an interface and by implementing it one can create a custom scope in the spring container org.springframework.beans.factory.config.Scope
是一个接口,通过实现它,可以在spring容器中创建一个自定义范围
public class RegionScope implements Scope {
private final ThreadLocal regionScope = new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
}
};
public Object get(String name, ObjectFactory objectFactory) {
Map scope = (Map) regionScope.get();
Object object = scope.get(name);
if (object == null) {
object = objectFactory.getObject();
scope.put(name, object);
}
return object;
}
public Object remove(String name) {
Map scope = (Map) regionScope.get();
return scope.remove(name);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.