有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring引导未找到线程绑定请求

我用一些restcontroller端点建立了一个springboot项目,等等。 一切正常

但现在我想安排“全部保存到弹性部分”。 使用邮递员一切正常

但是,当我尝试调用scheduler类中的服务方法时,出现了以下错误:

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;
    }

}

会议主题:

 @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) 个答案