java - Spring boot 未找到线程绑定请求
问题描述
我建立了一个带有一些restcontroller端点等的spring boot项目。一切正常。
但现在我想安排全部保存到弹性部分。使用邮递员一切正常。
但是,当我尝试在调度程序类中调用服务方法时,出现以下错误:
错误休息模板:
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 作为 Scope
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);
}
}
休息过滤器:
@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.");
}
}
有人知道我该怎么做才能解决我的问题吗?
解决方案
推荐阅读
- javascript - 是否有任何回调可以在 ajax 发送之后但在成功返回之前用于轮询目的?
- r - 过滤掉转发和回复的 Twitter API 查询
- ios - SceneKit在旋转后获取节点位置
- python - 导入 csv 文件时 csv.reader 和 .read 的区别
- android - 原因:重复条目:com/google/vr/cardboard/AndroidNCompat.class
- bash - 在 shell 脚本 bash 中获取一天的结束时间
- kotlin - RxJava2如何将2个单列表加入一个列表
- c# - 设置拆分视图控制器 Xamarin.iOS
- php - 如何使用stripe api汇款到其他人的银行账户
- ruby-on-rails - 无法弄清楚如何在 Rails 应用程序中添加多态标签