1.Meta上下文是平台传参的核心,千万别滥用,业务系统不得自行new Meta(),如已使用,请检查后去掉,优先改掉启动事件方法里的代码

2.当同步方法中需要meta时,应该通过BaseContextHandle.getMeta()来获取上下文信息;

3.当异步方法中需要meta时,应该调用rs.callAsync,不得自行创建线程

4.创建自己的 new Meta(),不要在平台创建的线程里使用

适用场景
比如Netty创建的线程、xxljob创建的线程,这些线程启动时没有meta对象,不走rpcController,但又要调用模型的服务


 //1.正确的写法:一定要使用try-catch-finally语法 在finally close
 @MethodService(description = "创建用户", name = "newMeta")
    public void newMeta(String id, int age, int times) {

        Meta meta = null;
        try {
            meta = new Meta(Meta.SUPERUSER, new HashMap<>());

            // 第2步:设置meta到线程变量
            BaseContextHandler.setMeta(meta);
            /**
             * TODO第3步:处理自己的业务逻辑 TestRole role = new TestRole(); role.setRoleName("test"); role.set("remark", "测试");
             * role.create();
             * 
             * 
             * 
             */
            // 第4步:刷新所有的数据到数据库
            meta.flush();

        } catch (Exception e) {
			// 第5步:异常设置setError=true,会回滚
            if (meta != null) {
                meta.setError(true);
            }
            throw e;
        } finally {
			// 第6步:调用close关闭连接和commit
            if (meta != null) {
                meta.close();
            }
            // 第6步:清理线程变量
            BaseContextHandler.remove();
        }
    }

5.错误的写法,不能使用:try-with-resources,这种会导致事物不会回滚

因为当try-with-resources中的代码块执行完毕后,或当块中的代码抛出异常时,系统会自动调用close()方法关闭资源。会先执行close方法,这个时候meta.getError()返回值还是false,导致事物提交了。然后再执行 Exception里面的代码块,这个时候就晚了,事物已经提交了。



//2.错误的写法,不能使用:try-with-resources,这种会导致事物不会回滚。
  
  @MethodService(description = "创建用户",name = "newMetaNoRollback")
  public void newMetaNoRollback(String id, int age,int times) {

      try (Meta meta = new Meta(Meta.SUPERUSER, new HashMap<>())) {
          // 第2步:设置meta到线程变量
          BaseContextHandler.setMeta(meta);
          /**
           * TODO第3步:处理自己的业务逻辑 TestRole role = new TestRole(); role.setRoleName("test"); role.set("remark", "测试");
           * role.create();
           * 
           * 
           * 
           */
          loopData(id, age, times);

          // 第4步:刷新所有的数据到数据库
          meta.flush();
      } catch (Exception e) {
          e.printStackTrace();  
          BaseContextHandler.getMeta().setError(true);
          throw e;
      } finally {
          // 第6步:清理线程变量
          BaseContextHandler.remove();
      }

  }