Skip to content

Commit 183987c

Browse files
committed
异步任务扩展 - ThreadLocal上下文拷贝示例
1 parent 7415b82 commit 183987c

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

spring-boot-data-aggregator-example/src/main/java/io/github/lvyahui8/spring/example/context/ExampleAppContext.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ public static String getUsername() {
2828
return LOGGED_USER.get() != null ? LOGGED_USER.get().getUsername() : null;
2929
}
3030

31+
public static User getUser() {
32+
return LOGGED_USER.get();
33+
}
34+
3135
public static void remove() {
3236
LOGGED_USER.remove();
3337
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
spring.main.banner-mode=off
22
io.github.lvyahui8.spring.base-packages=io.github.lvyahui8.spring.example
33
io.github.lvyahui8.spring.ignore-exception=false
4-
io.github.lvyahui8.spring.task-wrapper-class=io.github.lvyahui8.spring.aggregate.service.AsyncQueryTaskWrapperAdapter
4+
io.github.lvyahui8.spring.task-wrapper-class=io.github.lvyahui8.spring.example.wrapper.CustomAsyncQueryTaskWrapper
55
example.logging=true

0 commit comments

Comments
 (0)