继上一篇Mybatis通过Interceptor来简单实现影子表进行动态sql读取和写入 地址:https://my.oschina.net/u/3266761/blog/3014017
之后留了一个小坑,那就是希望能够根据控制层传输过来的是否采用影子表标识来动态的进行影子表的读取和写入,而不是写死在代码中
此次的目的就是解决这个问题:结合之前写的一篇文章:ThreadLocal实现线程安全 地址:https://my.oschina.net/u/3266761/blog/2032404
这次解决的方案就是结合ThreadLocal进行解决的,首先对ThredLocal进行一个简单的总结:
引用自:http://www.iteye.com/topic/103804
首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。
另外,说ThreadLocal使得各线程能够保持各自独立的一个对象,并不是通过ThreadLocal.set()来实现的,而是通过每个线程中的new 对象 的操作来创建的对象,每个线程创建一个,不是什么对象的拷贝或副本。通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象,ThreadLocal实例是作为map的key来使用的。
如果ThreadLocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的ThreadLocal.get()取得的还是这个共享对象本身,还是有并发访问问题。
下面来看一个hibernate中典型的ThreadLocal的应用:
1private static final ThreadLocal threadSession = new ThreadLocal(); 2 3public static Session getSession() throws InfrastructureException { 4 Session s = (Session) threadSession.get(); 5 try { 6 if (s == null) { 7 s = getSessionFactory().openSession(); 8 threadSession.set(s); 9 } 10 } catch (HibernateException ex) { 11 throw new InfrastructureException(ex); 12 } 13 return s; 14}
可以看到在getSession()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionFactory().openSession()来创建一个session,再将session set到线程中,实际是放到当前线程的ThreadLocalMap这个map中,这时,对于这个session的唯一引用就是当前线程中的那个ThreadLocalMap(下面会讲到),而threadSession作为这个值的key,要取得这个session可以通过threadSession.get()来得到,里面执行的操作实际是先取得当前线程中的ThreadLocalMap,然后将threadSession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。
显然,其他线程中是取不到这个session的,他们也只能取到自己的ThreadLocalMap中的东西。要是session是多个线程共享使用的,那还不乱套了。
试想如果不用ThreadLocal怎么来实现呢?可能就要在action中创建session,然后把session一个个传到service和dao中,这可够麻烦的。或者可以自己定义一个静态的map,将当前thread作为key,创建的session作为值,put到map中,应该也行,这也是一般人的想法,但事实上,ThreadLocal的实现刚好相反,它是在每个线程中有一个map,而将ThreadLocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了,不知道除了这些还有什么其他的好处。
总之,ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。归纳了两点:
1。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。
2。将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
当然如果要把本来线程共享的对象通过ThreadLocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。
ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。 这次就很合适
首先需要定义一个静态全局变量,类型是ThredLocal<Boolean>类型的,用来判断是否需要进行测试,如果是测试的话,则进行影子表的读写
1package cn.chinotan.dto.request; 2 3import java.io.Serializable; 4 5/** 6 * @program: test 7 * @description: 公共请求 8 * @author: xingcheng 9 * @create: 2019-03-02 17:18 10 **/ 11public class CommonRequest implements Serializable { 12 13 private static final long serialVersionUID = -2617189175983301155L; 14 15 public static ThreadLocal<Boolean> isTest = new ThreadLocal<Boolean>() { 16 @Override 17 protected Boolean initialValue() { 18 return false; 19 } 20 }; 21 22 public static Boolean isTest() { 23 return CommonRequest.isTest.get(); 24 } 25 26 public static void setTest(Boolean test) { 27 CommonRequest.isTest.set(test); 28 } 29}
接下来定义一个controller切面,对请求进行拦截,将测试变量记录在当前的线程的ThreadLocalMap中,之后mybatis的Interceptor从当前线程无需参数进行拿取,之后便可以进行判断是否需要进行影子表的操作
1package cn.chinotan.interceptor; 2 3import cn.chinotan.dto.request.CommonRequest; 4import com.alibaba.fastjson.JSONObject; 5import org.apache.commons.io.IOUtils; 6import org.apache.commons.lang3.StringUtils; 7import org.springframework.web.servlet.HandlerInterceptor; 8 9import javax.servlet.http.HttpServletRequest; 10import javax.servlet.http.HttpServletResponse; 11import java.util.Objects; 12 13/** 14 * @program: test 15 * @description: 16 * @author: xingcheng 17 * @create: 2019-03-02 18:29 18 **/ 19public class TestInterceptor implements HandlerInterceptor { 20 21 @Override 22 public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { 23 String isTestHeader = httpServletRequest.getHeader("isTest"); 24 // 先从header中去,取不到就从queryParam中取 25 if (StringUtils.isNotBlank(isTestHeader)) { 26 Boolean isTestBoolean = Objects.equals(isTestHeader, "true"); 27 CommonRequest.setTest(isTestBoolean); 28 } else { 29 String isTestParam = httpServletRequest.getParameter("isTest"); 30 if (StringUtils.isNotBlank(isTestParam)) { 31 Boolean isTestBoolean = Objects.equals(isTestParam, "true"); 32 CommonRequest.setTest(isTestBoolean); 33 } 34 } 35 return true; 36 } 37 38} 39 40 41package cn.chinotan.config; 42 43import cn.chinotan.interceptor.TestInterceptor; 44import org.springframework.context.annotation.Configuration; 45import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 46import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 47 48/** 49 * @program: test 50 * @description: 51 * @author: xingcheng 52 * @create: 2019-03-02 18:33 53 **/ 54@Configuration 55public class WebAppConfig implements WebMvcConfigurer { 56 57 @Override 58 public void addInterceptors(InterceptorRegistry registry){ 59 registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**"); 60 } 61 62} 63 64 65package cn.chinotan.interceptor; 66 67import cn.chinotan.aop.TableConfig; 68import cn.chinotan.controller.UserController; 69import cn.chinotan.dto.request.CommonRequest; 70import cn.chinotan.service.Strategy; 71import cn.chinotan.service.impl.BakStrategy; 72import org.apache.commons.lang3.StringUtils; 73import org.apache.ibatis.executor.statement.StatementHandler; 74import org.apache.ibatis.mapping.BoundSql; 75import org.apache.ibatis.mapping.MappedStatement; 76import org.apache.ibatis.plugin.*; 77import org.apache.ibatis.reflection.MetaObject; 78import org.apache.ibatis.reflection.SystemMetaObject; 79import org.slf4j.Logger; 80import org.slf4j.LoggerFactory; 81import org.springframework.beans.factory.annotation.Autowired; 82import org.springframework.stereotype.Component; 83 84import java.lang.reflect.ParameterizedType; 85import java.lang.reflect.Proxy; 86import java.lang.reflect.Type; 87import java.sql.Connection; 88import java.util.Map; 89import java.util.Properties; 90 91/** 92 * 完成插件签名: 93 * 告诉MyBatis当前插件用来拦截哪个对象的哪个方法 94 * type 指四大对象拦截哪个对象, 95 * method : 代表拦截哪个方法 ,在StatementHandler 中查看,需要拦截的方法 96 * args :代表参数 97 */ 98@Component 99@Intercepts({ 100 @Signature(type = StatementHandler.class, method = "prepare", args = { 101 Connection.class, Integer.class})}) 102public class ShareStatementPlugin implements Interceptor { 103 104 private static final Logger LOG = LoggerFactory.getLogger(ShareStatementPlugin.class); 105 106 @Autowired 107 private Map<String, Strategy> strategyMap; 108 109 @Override 110 public Object intercept(Invocation invocation) throws Throwable { 111 StatementHandler statementHandler = realTarget(invocation.getTarget()); 112 MetaObject metaObject = SystemMetaObject.forObject(statementHandler); 113 doTable(statementHandler, metaObject); 114 return invocation.proceed(); 115 } 116 117 private void doTable(StatementHandler handler, MetaObject metaStatementHandler) throws ClassNotFoundException { 118 BoundSql boundSql = handler.getBoundSql(); 119 String originalSql = boundSql.getSql(); 120 121 if (originalSql != null && !originalSql.equals("")) { 122 LOG.info("分表前的SQL:{}", originalSql); 123 MappedStatement mappedStatement = (MappedStatement) metaStatementHandler 124 .getValue("delegate.mappedStatement"); 125 String id = mappedStatement.getId(); 126 String className = id.substring(0, id.lastIndexOf(".")); 127 Class<?> classObj = Class.forName(className); 128 Class baseEntity = null; 129 Type[] interfacesTypes = classObj.getGenericInterfaces(); 130 for (Type type : interfacesTypes) { 131 if (type instanceof ParameterizedType) { 132 ParameterizedType interfacesType = (ParameterizedType) interfacesTypes[0]; 133 Type t = interfacesType.getActualTypeArguments()[0]; 134 baseEntity = (Class) t; 135 } 136 } 137 // 根据配置自动生成分表SQL 138 TableConfig tableConfig = classObj.getAnnotation(TableConfig.class); 139 // 获取表名 并进行相应转化 140 String tableName = baseEntity.getSimpleName().toLowerCase(); 141 if (StringUtils.isNotBlank(tableConfig.value())) { 142 tableName = tableConfig.value(); 143 } 144 145 if (tableConfig != null && tableConfig.isTest()) { 146 // 获取策略来处理 147 Strategy strategy = strategyMap.get(tableConfig.strategy()); 148 if (strategy instanceof BakStrategy) { 149 ThreadLocal<Boolean> isTest = CommonRequest.isTest; 150 Boolean aBoolean = isTest.get(); 151 LOG.info("是否测试:{}", aBoolean); 152 if (aBoolean) { 153 String convertedSql = originalSql.replaceAll(tableName, strategy.convert(tableName)); 154 metaStatementHandler.setValue("delegate.boundSql.sql", convertedSql); 155 LOG.info("分表后的SQL:{}", convertedSql); 156 } 157 } 158 } 159 } 160 } 161 162 @Override 163 public Object plugin(Object target) { 164 if (target instanceof StatementHandler) { 165 return Plugin.wrap(target, this); 166 } 167 return target; 168 } 169 170 @Override 171 public void setProperties(Properties properties) { 172 } 173 174 /** 175 * 获得真正的处理对象,可能多层代理 176 * 177 * @param target 178 * @param <T> 179 * @return 180 */ 181 public static <T> T realTarget(Object target) { 182 if (Proxy.isProxyClass(target.getClass())) { 183 MetaObject metaObject = SystemMetaObject.forObject(target); 184 return realTarget(metaObject.getValue("h.target")); 185 } 186 return (T) target; 187 } 188}
请求Controller:
1package cn.chinotan.controller; 2 3 4import cn.chinotan.entity.User; 5import cn.chinotan.service.UserService; 6import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; 7import com.baomidou.mybatisplus.core.metadata.IPage; 8import com.baomidou.mybatisplus.extension.plugins.pagination.Page; 9import org.springframework.beans.factory.annotation.Autowired; 10import org.springframework.web.bind.annotation.*; 11 12import java.time.LocalDateTime; 13import java.util.Date; 14import java.util.List; 15 16/** 17 * <p> 18 * 用户表 前端控制器 19 * </p> 20 * 21 * @author xingcheng 22 * @since 2019-02-16 23 */ 24@RestController 25@RequestMapping("/user") 26public class UserController { 27 28 @Autowired 29 UserService userService; 30 31 @GetMapping("/list") 32 public Object list() { 33 List<User> list = userService.list(); 34 return list; 35 } 36 37 @GetMapping("/page/list/{current}/{size}") 38 public Object page(@PathVariable("current") Long current, @PathVariable("size") Long size) { 39 Page<User> objectPage = new Page<>(current, size); 40 IPage<User> page = userService.page(objectPage); 41 return page; 42 } 43 44 @GetMapping("/save/{name}") 45 public Object save(@PathVariable("name") String name) { 46 User user = new User(); 47 user.setCreateTime(LocalDateTime.now()); 48 user.setUpdateTime(LocalDateTime.now()); 49 user.setName(name); 50 boolean save = userService.save(user); 51 return save; 52 } 53 54 @GetMapping("/update/{name}") 55 public Object update(@PathVariable("name") String name) { 56 User user = new User(); 57 user.setId(1L); 58 user.setCreateTime(LocalDateTime.now()); 59 user.setUpdateTime(LocalDateTime.now()); 60 user.setName(name); 61 boolean update = userService.updateById(user); 62 return update; 63 } 64} 65
下面是测试过程:




接下来,进行写入操作:


分别插入测试和非测试数据参数,看看数据库的情况:


大公告成