在springboot应用程序中使用rest模板调用以@async注解的方法

pkln4tw6  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(394)

我对@async和rest模板调用有问题;这是我的主要应用程序类,带有一个任务执行器bean和enablesync注解

@SpringBootApplication
@ComponentScan({"org.***"})
@EnableAspectJAutoProxy
@EnableAsync
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
@EnableFeignClients(basePackages = {"org.service.feign"})
public class MainApplication extends SpringBootServletInitializer {

    /**
     * <p>main.</p>
     *
     * @param args an array of {@link java.lang.String} objects.
     */
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

    @Bean(name = "threadPoolTaskExecutor")
      public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix(“CustomLookup-");
        executor.initialize();
        return executor;
      }
    /**
     * Configure.
     *
     * @param application the application
     * @return the spring application builder
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MainApplication.class);
    }

    /**
     * <p>requestContextListener.</p>
     *
     * @return a {@link org.springframework.web.context.request.RequestContextListener} object.
     */
    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
   }
}

这是我在rest控制器中调用的带有异步注解的测试服务:

@Service
public class TestService {

    @Async("threadPoolTaskExecutor")
    public ResponseEntity<Object> test()
            throws Exception{
        PagedRequest<SearchRequest> request = new PagedRequest<SearchRequest>();

        SearchRequest filters = new Request();

        filters.setCod(“abcdeg");

        request.setFilters(filters);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(new RestInterceptor()));  // here I set a custom headers
        final HttpHeaders theJsonHeader = new HttpHeaders();
        theJsonHeader.setContentType(MediaType.APPLICATION_JSON);
        final MultiValueMap<String, Object> theMultipartRequest = new LinkedMultiValueMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String someJsonString = objectMapper.writeValueAsString(request);
        theMultipartRequest.add("request", new HttpEntity<>(someJsonString, theJsonHeader));
        ResponseEntity<Object> response = null;
        final HttpEntity<PagedRequest<SearchRequest>> theHttpEntity = new HttpEntity<>(request, theJsonHeader);

        String path = “http://...”; //url removed for privacy

        response = restTemplate.postForEntity(path, theHttpEntity, Object.class);
        return response;

    }

}

此服务返回rest模板上的空指针;这是stacktrace

java.lang.NullPointerException: null
    at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:61) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:773) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:452) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.REL

这里是我在resttemplate中添加的restintercept代码

public class RestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null)
            return null;

        HttpServletRequest req = requestAttributes.getRequest();
        if (req == null || req.getHeader(PrevConstants.USER_KEY)==null || req.getHeader(PrevConstants.JWT_HEADER_NAME)==null)
            return null;

        String userKey = req.getHeader(PrevConstants.USER_KEY);

        String jwt = req.getHeader(PrevConstants.JWT_HEADER_NAME);

        if (jwt == null) {
            jwt = "custom jwt";
        }

        else if ( !jwt.startsWith("Bearer")) {                     jwt = "Bearer " + jwt;                 }

        request.getHeaders().set(PrevConstants.USER_KEY, userKey);
        request.getHeaders().set(PrevConstants.JWT_HEADER_NAME, jwt);         

        ClientHttpResponse response = execution.execute(request, body);
        return response;
    }
}

但是如果我删除,@enablesync和@async,那么简单的rest模板就可以完美地工作。有什么问题吗?我不知道。谢谢你的回复

fnx2tebb

fnx2tebb1#

RequestContextHolder 保存当前线程正在处理的请求的上下文。当你使用 @Async 您的拦截器在处理请求的线程的不同线程上被调用。因此, RequestContextHolder.getRequestAttributes() 返回 null 然后你的拦截器返回一个 null 答复。遵守合同 ClientHttpRequestInterceptor#intercept 它必须返回一个非空值,因此 null 响应导致失败。
如果你想用 @Async ,您必须检索 RequestAttributes 在rest控制器中,然后将它们传递到 TestService 作为 test 方法。然后,您可以创建 RestInterceptor 使用属性,而不是使用 RequestContextHolder 要访问它们:

@Async("threadPoolTaskExecutor")
public ResponseEntity<Object> test(RequestAttributes requestAttributes) throws Exception {
    // …
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(Collections.singletonList(new RestInterceptor(requestAttributes)));
    // …
}
rt4zxlrg

rt4zxlrg2#

@andy,我已经直接从我的rest控制器传递了第一个requestattributes和第二个片刻的httpservletrequest,但结果是相同的,nullpointer。你有我能看到的剪报吗?

@Async("threadPoolTaskExecutor")
public ResponseEntity<Object> test(HttpServletRequest req) throws Exception {
    // …
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(Collections.singletonList(new RestInterceptor(req)));
    // …
}

public class RestInterceptor implements ClientHttpRequestInterceptor {
private HttpServletRequest req;

public RestInterceptor(HttpServletRequest req){
    this.req=req;
}
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

        HttpServletRequest req = this.req;
        if (req == null || req.getHeader(PrevConstants.USER_KEY)==null || req.getHeader(PrevConstants.JWT_HEADER_NAME)==null)
            return null;

        String userKey = req.getHeader(PrevConstants.USER_KEY);

        String jwt = req.getHeader(PrevConstants.JWT_HEADER_NAME);

        if (jwt == null) {
            jwt = "custom token";
        }

        else if ( !jwt.startsWith("Bearer")) {                     jwt = "Bearer " + jwt;                 }

        request.getHeaders().set(PrevConstants.USER_KEY, userKey);
        request.getHeaders().set(PrevConstants.JWT_HEADER_NAME, jwt);         

        ClientHttpResponse response = execution.execute(request, body);
        return response;
    }

相关问题