简体   繁体   中英

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). I pass the request headers received by my service down to these webservices. However since these requests are fired in an async manner , these typically execute after my REST service returns a response. This causes HTTP request object to be lost. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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