DynamicDataSourceHolder.java 815 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package com.happy.myDataSource;
  2. public class DynamicDataSourceHolder {
  3. // 写库数据源key
  4. private static final String MASTER = "master";
  5. // 读库数据源key
  6. private static final String SLAVE = "slave";
  7. // 使用ThreadLocal记录当前数据源Key
  8. private static final ThreadLocal<String> holder = new ThreadLocal<String>();
  9. /**
  10. * 设置数据源key
  11. *
  12. * @param key
  13. */
  14. public static void putDataSourceKey(String key) {
  15. holder.set(key);
  16. }
  17. /**
  18. * 获取数据源key
  19. *
  20. * @return
  21. */
  22. public static Object getDataSourceKey() {
  23. return holder.get();
  24. }
  25. /**
  26. * 标记写库
  27. */
  28. public static void markMaster() {
  29. putDataSourceKey(MASTER);
  30. }
  31. /**
  32. * 标记读库
  33. */
  34. public static void markSlave() {
  35. putDataSourceKey(SLAVE);
  36. }
  37. }