简介:
接上篇
java开源项目源码阅读 mall4cloud-CSDN博客
commom -database
Mybatis配置
配置一个全局的包扫描路径 @MapperScan
分布式id生成策略 美团单点策略
创建一个字段注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributedId {
String value();
}
mybatis拦截器设置规则
首先判断是否是插入操作
然后判断字段是否有注解
最后调用分布式id接口设置字段
分布式id生成代码:
private void generatedKey(Object parameter) throws Throwable {
Field[] fieldList = parameter.getClass().getDeclaredFields();
for (Field field : fieldList) {
if (!field.getType().isAssignableFrom(Long.class)) {
break;
}
DistributedId annotation = field.getAnnotation(DistributedId.class);
if (annotation == null) {
break;
}
field.setAccessible(true);
if (field.get(parameter) != null) {
break;
}
ServerResponseEntity<Long> segmentIdResponseEntity = segmentFeignClient.getSegmentId(annotation.value());
if (segmentIdResponseEntity.isSuccess()) {
// 这里设置分布式id
field.set(parameter,segmentIdResponseEntity.getData());
} else {
logger.error("can't get distributed id !!!! ");
throw new DyCloudException(ResponseEnum.EXCEPTION);
}
}
}
分布式事务:
采用seata at模式
在所有feign请求上面,都设置全局锁。
业务中开启全局事务和本地事务
@GlobalTransactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@Component
@ConditionalOnClass({RequestInterceptor.class, GlobalTransactional.class})
public class SeataRequestInterceptor implements RequestInterceptor {
private static final Logger logger = LoggerFactory.getLogger(SeataRequestInterceptor.class);
@Override
public void apply(RequestTemplate template) {
String currentXid = RootContext.getXID();
if (StrUtil.isNotBlank(currentXid) && !template.url().startsWith(Auth.CHECK_TOKEN_URI) && !template.url().startsWith(Auth.CHECK_RBAC_URI)) {
template.header(RootContext.KEY_XID, currentXid);
}
}
}