Spring WebFlux在退出端点方法返回Mono后做了什么?



让我们考虑以下代码库:

@GetMapping("/test")
public Mono<org.springframework.security.oauth2.jwt.Jwt> test {
Mono<org.springframework.security.oauth2.jwt.Jwt> mono =
ReactiveSecurityContextHolder.getContext()
.map(securityContext ->(org.springframework.security.oauth2.jwt.Jwt) securityContext.getAuthentication().getPrincipal());
org.springframework.security.oauth2.jwt.Jwt jwtFromMono = firstMono
.toFuture()
.get();
System.out.println("jwt value is " + jwtFromMono);
return mono ;
}
结果我们看到如下控制台输出:
jwt value is null

和后面的http响应:

{
"tokenValue": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJlVzJhNVlVRXRoTFBYeTBVUWlXQTZudWtOQ2UtU0x2aU9IVlZ5RnJyVW9FIn0.eyJleHAiOjE2NzM2MzkwOTQsImlhdCI6MTY3MzYzODc5NCwianRpIjoiYTJjZTFmYWUtZWU1NS00MDc4LWE0NDctYzdkNDU3MWRhNWYwIiwiaXNzIjoiaHR0cHM6Ly9hdXRoLTM3My05OWJhYy5kYnAuaW5uby50ZWNoL3JlYWxtcy90ZWNocGxhdCIsInN1YiI6Ijk5ZGZmZDliLWQ5OWEtNGM5Zi1hZWNhLTgxMThlMTYyOTU3MCIsInR5cCI6IkJlYXJlciIsImF6cCI6InBsYXQtZWNtLWNhbGxlci1jbGllbnQiLCJzZXNzaW9uX3N0YXRlIjoiNTQ4YzlhMTctZTdjYi00NzkxLTg5ZWUtMWU3OTU3ODQ2YWI3Iiwic2NvcGUiOiIiLCJzaWQiOiI1NDhjOWExNy1lN2NiLTQ3OTEtODllZS0xZTc5NTc4NDZhYjciLCJyb2xlcyI6WyJFQ01fVVNFUiJdfQ.Nfm-kqOp57bIuou8Qu0Gd4p06eUnbcKwEhxMGWGGqQN1Xh_czT2pNhqDQClsFVeyloIZeuKLCXvCJcK0-BrLqKwIWeQWX8lmmDEgdjwvPm9Uaypq2K1ur8OyzYTAocXRkL6_tcyP64th2m6xL5pVGeoqavdcDBR2e15_P8gHZaAzi8M6ke5V_uTNA6DNJrLAwMmHHjieWimBdFtxb5QFDtmfHWgyChYRQIvJVO74EKdXLv_XT_9hjByG2uQ5x4tEEtqZeWALlAMMzvcgHcA8llg5rHtvyGUl9Yv4d2oLoyHy22zvMO3BfxjpA4W19ps6vLHFLoUK9alcStuZlwSvPA",
"issuedAt": "2023-01-13T19:39:54Z",
"expiresAt": "2023-01-13T19:44:54Z"
...

结果很有代表性:

  1. 当我们手动调用.toFuture().get()时,我们接收null

  2. 当我们从端点方法返回Mono时-结果包含来自安全上下文的数据(非空的Jwt令牌)

所以Spring在幕后做了一些工作。工作是什么?有没有办法从我的端点方法手动调用它?

我建议将日志记录语句作为发布程序的一部分,以便在订阅mono时记录日志,而不是尝试尽早调用发布程序。即:

@GetMapping("/test")
public Mono<org.springframework.security.oauth2.jwt.Jwt> test() {
return ReactiveSecurityContextHolder.getContext()
.map(securityContext -> (org.springframework.security.oauth2.jwt.Jwt) securityContext.getAuthentication().getPrincipal())
.doOnNext(jwt -> System.out.println("jwt value is " + jwt));
}

当返回响应时,我实际上无法回答在幕后发生了什么,但是在return语句之后的某个时刻,mono将被订阅。响应式管道中的步骤通常只有在mono被订阅后才会被评估,这可以解释日志语句中的空值。

相关内容

  • 没有找到相关文章

最新更新