春季启动找不到线程绑定的请求

时间:2019-11-13 13:10:08

标签: java multithreading rest spring-boot scheduler

我建立了一个带有一些restcontroller端点的spring boot项目,依此类推。 一切正常。

但是现在我要安排将全部保存到弹性部分。 使用邮递员,一切正常。

但是当我尝试在调度程序类中调用服务方法时,出现以下错误:

错误RestTemplate:

java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

将SessionAttribute错误作为范围

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.sessionAttribute': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

我的 sessionAttribute 类注释为作用域的错误不是bean ...无法访问它。

调度程序:我也尝试直接在调度程序中自动连接restTemplate,但存在相同的错误。

@Component
@Slf4j
@EnableScheduling
public class ElasticScheduler {

    @Autowired
    private PPMSCalls ppmsCalls;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${seminarbuchung.ppms.timeout}")
    public int timeout;

    // For testing every 30 minutes log it.
    @Scheduled(cron = "0 */1 * ? * *")
    public void testingScheduler() throws SemiException {

        log.info("SCHEDULER - PPMS scheduler starting");

        try {

            ResponseEntity resp = ppmsCalls.saveUpdateAllSeminareToElasticSearch();

        } catch (SemiException e) {
            log.error("ERROR Scheduler - PPMS to elastic.", e.getException());
        }

        log.info("SCHEDULER - PPMS scheduler done.");
    }
}

我的RestClientConfig看起来像:

@Configuration
@Slf4j
public class RestClientConfig {

    @Value("${seminarbuchung.ppms.timeout}")
    public int timeout;

    @Bean
    public RestTemplate restTemplate() throws SemiException {

        log.info("Setting up rest template.");

        try {
            final TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
            final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();
            final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,
                    new String[]{"TLSv1.2", "TLSv1.1"}, null, new NoopHostnameVerifier());
            final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
            final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setConnectTimeout(timeout);
            requestFactory.setReadTimeout(timeout);

            requestFactory.setHttpClient(httpClient);
            final RestTemplate restTemplate = new RestTemplate(requestFactory);

            restTemplate.setRequestFactory(requestFactory);
            restTemplate.setInterceptors(Collections.singletonList(new CustomHTTPClientInterceptor()));

            log.info("ResTemplate bean activated.");

            return restTemplate;
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            throw new SemiException("ERROR creating restTemplate bean.", "", e);
        }
    }

    @Bean
    public FilterRegistrationBean restRegistrationBean() {
        log.info("Setting up restRegistrationBean");
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new RestFilter());
        filterRegistrationBean.setUrlPatterns(Collections.singletonList("/*"));
        log.info("FilterRegistration bean activated.");

        return filterRegistrationBean;
    }

}

SessionAttribute:

 @Component
@Scope(value = "session", proxyMode= ScopedProxyMode.TARGET_CLASS)
@Data
public class SessionAttribute implements Serializable {

    private String access_token;
    private String token_type;
    private long expires_in;
    private long tokenSetTime;

}

服务:

public class PPMSCallsImpl implements PPMSCalls {

    private final RestTemplate restTemplate;
    private SessionAttribute sessionAttribute;

// autowired both

...
 private ResponseEntity<Object> getResult(final String url, final HttpMethod httpMethod, final HttpEntity<?> httpEntity) throws SemiException {
        try {

            // get sessionAttribute.get...
            return restTemplate.exchange(url, httpMethod, httpEntity, Object.class);

        } catch (HttpClientErrorException e) {
            throw new SemiException("Problem with connection", e.getStatusCode().toString(), e);
        } catch (Exception e) {
            throw new SemiException("Has to be defined correctly.", "", e);
        }
    }

RestFilter:

@Slf4j
@Component
public class RestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("Filter activated.");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) servletRequest;
        final HttpServletResponse res = (HttpServletResponse) servletResponse;
        final Cookie[] allCookies = req.getCookies();
        if (allCookies != null) {
            Cookie session = Arrays.stream(allCookies).filter(x -> x.getName().equals("JSESSIONID")).findFirst().orElse(null);

            if (session != null) {
                session.setHttpOnly(true);
                session.setSecure(true);
                res.addCookie(session);
            }
        }
        filterChain.doFilter(req, res);
    }

    @Override
    public void destroy() {
        log.info("Filter destroyed.");
    }
}

有人知道我该怎么做才能解决我的问题?

0 个答案:

没有答案