|
| 1 | +package io.github.lvyahui8.spring.example.wrapper; |
| 2 | + |
| 3 | +import io.github.lvyahui8.spring.aggregate.service.AsyncQueryTaskWrapper; |
| 4 | +import io.github.lvyahui8.spring.example.context.ExampleAppContext; |
| 5 | +import io.github.lvyahui8.spring.example.context.RequestContext; |
| 6 | +import io.github.lvyahui8.spring.example.model.User; |
| 7 | +import lombok.extern.slf4j.Slf4j; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author lvyahui (lvyahui8@gmail.com,lvyahui8@126.com) |
| 11 | + * @since 2020/1/5 13:10 |
| 12 | + */ |
| 13 | +@Slf4j |
| 14 | +public class CustomAsyncQueryTaskWrapper implements AsyncQueryTaskWrapper { |
| 15 | + |
| 16 | + private Long tenantId; |
| 17 | + private User user; |
| 18 | + |
| 19 | + @Override |
| 20 | + public void beforeSubmit() { |
| 21 | + /* 提交任务前, 先从当前线程拷贝出ThreadLocal中的数据到任务中 */ |
| 22 | + log.info("asyncTask beforeSubmit. threadName: {}",Thread.currentThread().getName()); |
| 23 | + this.tenantId = RequestContext.getTenantId(); |
| 24 | + this.user = ExampleAppContext.getUser(); |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public void beforeExecute(Thread taskFrom) { |
| 29 | + /* 任务提交后, 执行前, 在异步线程中用数据恢复ThreadLocal(Context) */ |
| 30 | + log.info("asyncTask beforeExecute. threadName: {}, taskFrom: {}",Thread.currentThread().getName(),taskFrom.getName()); |
| 31 | + RequestContext.setTenantId(tenantId); |
| 32 | + ExampleAppContext.setLoggedUser(user); |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public void afterExecute(Thread taskFrom) { |
| 37 | + /* 任务执行完成后, 清理异步线程中的ThreadLocal(Context) */ |
| 38 | + log.info("asyncTask afterExecute. threadName: {}, taskFrom: {}",Thread.currentThread().getName(),taskFrom.getName()); |
| 39 | + RequestContext.removeTenantId(); |
| 40 | + ExampleAppContext.remove(); |
| 41 | + } |
| 42 | +} |
0 commit comments