如何在多个线程上使用多数据库连接..
我知道如何动态地使用带有routingdataSource的数据库连接,但我认为它不是线程安全的,因为类是静态的。!!!
// first thread
ContextHolder.set("firstId");
mapper.select();
ContextHolder.clear(idFirst);
// second thread
ContextHolder.set("secondId");
mapper.select();
ContextHolder.clear(idFirst);
public class ContextHolder {
private static ThreadLocal<String> CONTEXT = new ThreadLocal<>();
public static void set(String dbType) {
CONTEXT.set(dbType);
}
public static String getClientDatabase() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}
喜欢这个代码。
public class Poller implements Runnable {
@Override
public List<Map<String, Object>> getNext() {
Map<String, Object> params = new HashMap<>();
ContextHolder.set(dbConnectionId);
List<Map<String, Object>> list = blogMapper.findAll(params)
ContextHolder.clear();
return list;
}
....
}
qq_笑_17
相关分类