1、底层实现
使用ThreadLocal,使用方法
public T get()
public void set(T value)
public void remove()
2、自定义上下文
package com.ybw.context.config;
import com.ybw.context.dto.TenantDTO;
/**
* @author ybw
* @version V1.0
* @className TenantContext
* @date 2022/9/30
**/
public class TenantContext {
private static final ThreadLocal<TenantDTO> context = new ThreadLocal<>();
/**
* 构造方法私有化
*
* @methodName: TenantContext
* @return:
* @author: ybw
* @date: 2022/9/30
**/
private TenantContext() {
}
/**
* 存放租户信息
*
* @param tenantDTO
* @methodName: set
* @return: void
* @author: ybw
* @date: 2022/9/30
**/
public static void set(TenantDTO tenantDTO) {
context.set(tenantDTO);
}
/**
* 获取组合信息
*
* @methodName: get
* @return: com.ybw.mybatis.multi.tenant.dto.TenantDTO
* @author: ybw
* @date: 2022/9/30
**/
public static TenantDTO get() {
return context.get();
}
/**
* 清除当前线程内引用,防止内存泄漏
*
* @methodName: remove
* @return: void
* @author: ybw
* @date: 2022/9/30
**/
public static void remove() {
context.remove();
}
}
3、定义dto
package com.ybw.context.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author ybw
* @version V1.0
* @className TenantDTO
* @date 2022/9/30
**/
@NoArgsConstructor
@AllArgsConstructor
@Data
public class TenantDTO {
/**
* 组合层级
*
* @author: ybw
* @date: 2022/9/30
**/
private Integer level;
/**
* 租户id
*
* @author: ybw
* @date: 2022/9/30
**/
private Long tenantId;
}
4、调用
package com.ybw.context.service;
/**
* @className TenantService
* @author ybw
* @date 2022/10/1
* @version V1.0
**/
public interface TenantService {
/**
*
* @methodName: print
* @return: void
* @author: ybw
* @date: 2022/10/1
**/
void print();
}
package com.ybw.context.service.impl;
import com.alibaba.fastjson2.JSON;
import com.ybw.context.config.TenantContext;
import com.ybw.context.dto.TenantDTO;
import com.ybw.context.service.TenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class TenantServiceImpl implements TenantService {
@Override
public void print() {
TenantDTO tenantDTO = TenantContext.get();
TenantContext.remove();
if (tenantDTO == null) {
return;
}
log.info("tenantDTO:{}", JSON.toJSONString(tenantDTO));
}
}
5、测试
package com.ybw.context.service;
import com.ybw.context.config.TenantContext;
import com.ybw.context.dto.TenantDTO;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@Slf4j
class TenantServiceTest {
@Resource
private TenantService tenantService;
@Test
void print() {
TenantContext.set(new TenantDTO(1,12L));
tenantService.print();
}
}
输出结果
[INFO ] 2022-10-01 22:45:13.207 [main] c.y.c.service.TenantServiceImpl - tenantDTO:{"level":1,"tenantId":12}
6、示例代码
share: 分享仓库 - Gitee.com