我想触发一个方法来创建 ArrayList
并将此列表返回
到callback-URL
。此方法可能需要一段时间才能生成数据,因此它应该是异步运行方法。
所以我有几个问题:
- 什么是
回调 URL
?我假设它是方法返回值的URL
? - 如何
返回
值
到回调URL
? 返回值后如何访问?
@Async @GetMapping("/createcustomer/{start}/{end}"){ public ArrayList<Customer> createCustomer(@PathVariable int start, @PathVariable int end) { //code to generate random data return arrayList; }
最佳答案
为了调用您的处理程序方法,您可以在前端使用 JavaScript 代码。以下是如何使用 axios 库执行此操作的示例:
axios.get('createcustomer/something/something')
.then(function (response) {
console.log(response);
// response.data will contain your json with returned list content
})
.catch(function (error) {
console.log(error);
});
您还需要像这样修改您的处理方法:
@ReponseBody
@GetMapping("createcustomer/{start}/{end}"){
public ArrayList<Customer> createCustomer(@PathVariable int start,
@PathVariable int end) {
//code to generate random data
return arrayList;
}
@ResponseBody 注释将导致 ArrayList 在响应正文中以 json 形式返回。或者,您可以将 @Controller 类注释更改为 @RestController。它将使该类中的所有处理程序方法返回给客户端。
这样,请求将是完全异步的,一旦可用,您就可以在前端代码中访问它。
编辑:
如果您想使用callback-url将此列表发送到其他地方,您可以使用RestTemplate发送以列表作为正文的post请求。您可以在处理程序方法中使用类似于此代码的内容:
String callback-URL = "http://my.server.com/customerListEndpoint";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<>(headers);
restTemplate.exchange(callback-URL,HttpMethod.POST,entity,ArrayList.class);
您需要一个可以将 post 请求映射到回调 URL 的端点。像这样的东西:
@PostMapping("/customerListEndpoint"){
public void createCustomer(@RequestBody ArrayList<Customer> arrayList) {
// do what you want with arrayList here
}
此外,请确保在某个使用 @Configuration 注释的类中配置 RestTemplate bean:
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setOutputStreaming(false);
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(requestFactory));
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
关于java - 异步运行方法返回值到回调URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49958254/