Mono在订阅时不会发出值。

huangapple go评论68阅读模式
英文:

Mono does not emit value when subscribed

问题

我试图在响应式Spring应用程序中使用Spring Security验证身份。在控制器中,我无法读取Mono<Authentication>的内容。当我订阅时,它不会发出任何值。我在控制器中有以下代码:

@Controller
public class TestConroller {

 public void test(){
   Mono<Authentication> monoAuth = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);
   monoAuth.subscribe(authentication -> validate(authentication));
 }
 private void validate(Authentication authentication){
   System.out.println(authentication.getPrincipal().getName());
 }
}

validate方法从未被调用。

英文:

I am trying to validate authentication in reactive spring application with Spring Security. I could not read content from Mono<Authentication> in the controller. It is not emitting any values when I subscribed. I have the following code in the controller:

@Controller
public class TestConroller {

 public void test(){
   Mono&lt;Authentication&gt; monoAuth=ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);
   monoAuth.subscribe(authentication-&gt;validate(authentication) 
 }
 private void validate(Authentication authentication){
   System.out.println(authentication.getPrincipal().getName());
 }
}

The validate method is never called

答案1

得分: 1

尽管 "在订阅之前什么都不会发生", 但你不需要显式调用 subscribe。如果返回 Mono&lt;T&gt;,WebFlux会在后台进行订阅。你只需要构建一个组合不同的响应式操作符的流。

public Mono&lt;String&gt; test() {
        return ReactiveSecurityContextHolder.getContext()
                .map(ctx -&gt; validate(ctx.getAuthentication()));
    }
    
    private String validate(Authentication authentication){
        String name = ((Principal) authentication.getPrincipal()).getName();

        // 验证
        return name;
    }
英文:

Although "nothing happens until you subscribe", you don't need to call subscribe explicitly. WebFlux will subscribe behind the scene if you return Mono&lt;T&gt;. You just need to build a flow combining different reactive operators.

public Mono&lt;String&gt; test() {
        return ReactiveSecurityContextHolder.getContext()
                .map(ctx -&gt; validate(ctx.getAuthentication()));
    }
    
    private String validate(Authentication authentication){
        String name = ((Principal) authentication.getPrincipal()).getName();

        // validate
        return name;
    }

huangapple
  • 本文由 发表于 2023年2月19日 00:26:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定