简体   繁体   English

Restful Spring Services中的会话范围

[英]Session Scope in Restful Spring Services

This question is related to this . 这个问题与有关。 I have a Restful service that invokes a number of webservices in an async fashion (using threads - fire and forget). 我有一个Restful服务,它以异步方式(使用线程-触发并忘记)调用许多Web服务。 I pass the request headers received by my service down to these webservices. 我将服务接收的请求标头传递给这些Web服务。 However since these requests are fired in an async manner , these typically execute after my REST service returns a response. 但是,由于这些请求是以异步方式触发的,因此通常在我的REST服务返回响应后执行。 This causes HTTP request object to be lost. 这将导致HTTP请求对象丢失。 Hence as suggested in this thread I am using session scope to retain the request headers. 因此,如该线程中所建议,我正在使用会话范围来保留请求标头。 Will this have any adverse impact that I should analyze. 这会对我产生任何不利影响吗? Is there a better approach that I must look at? 我必须考虑一种更好的方法吗?

If you start using session scope to store requests, your service is not RESTful anymore, because it's not stateless. 如果您开始使用会话作用域来存储请求,则您的服务不再是RESTful的,因为它不是无状态的。 I would suggest to avoid using session scope altogether. 我建议避免完全使用会话范围。

If you need to use request object in asynchronous thread (using Spring's @Async annotation), just pass it to asynchronous logic via parameter. 如果您需要在异步线程中使用请求对象(使用Spring的@Async批注),只需通过参数将其传递给异步逻辑即可。

Something like this: 像这样:

@Component
public class AsyncUserService {

  @Async("customTaskExecutor")
  public void updateOrAddUser(int id, HttpServletRequest request) throws {
    //do your stuff
  }
}

@Controller
@RequestMapping("/users")
public class UserController {
  private final AsyncUserService userService;

  @Autowired
  public UserController(AsyncUserService userService) {
    super();
    this.userService = userService;
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
  @ResponseStatus(HttpStatus.OK)
  public void putUser(@PathVariable("id") int identifier, HttpServletRequest request) {
    userService.updateOrAddUser(identifier, request);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM