本文整理匯總了Java中org.springframework.util.concurrent.ListenableFuture類的典型用法代碼示例。如果您正苦於以下問題:Java ListenableFuture類的具體用法?Java ListenableFuture怎麽用?Java ListenableFuture使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ListenableFuture類屬於org.springframework.util.concurrent包,在下文中一共展示了ListenableFuture類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: send
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
public void send(String topic, LifecycleEvent message) {
// the KafkaTemplate provides asynchronous send methods returning a Future
ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, message);
// register a callback with the listener to receive the result of the send asynchronously
future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
@Override
public void onSuccess(SendResult<String, Object> result) {
LOGGER.info("sent message='{}' with offset={}", message,
result.getRecordMetadata().offset());
}
@Override
public void onFailure(Throwable ex) {
LOGGER.error("unable to send message='{}'", message, ex);
}
});
}
示例2: submitListenable
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
public ListenableFuture<?> submitListenable (Runnable task)
{
ExecutorService executor = getThreadPoolExecutor ();
try
{
ListenableFutureTask<Object> future =
new ListenableFutureTask<Object> (task, null);
executor.execute (future);
return future;
}
catch (RejectedExecutionException ex)
{
throw new TaskRejectedException ("Executor [" + executor +
"] did not accept task: " + task, ex);
}
}
示例3: websyncDeptList
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@GetMapping(value="/webSyncDept/{id}.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<Department> websyncDeptList(@PathVariable("id") Integer id){
Callable<Department> callable = new Callable<Department>() {
public Department call() throws Exception {
ListenableFuture<Department> listenFuture = departmentServiceImpl.findAllFirstById(id);
listenFuture.addCallback(new ListenableFutureCallback<Department>(){
@Override
public void onSuccess(Department dept) {
result = dept;
}
@Override
public void onFailure(Throwable arg0) {
result = new Department();
}
});
return result;
}
};
return new WebAsyncTask<Department>(500, callable);
}
示例4: rest
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@GetMapping("/rest")
public DeferredResult<String> rest(int idx) {
DeferredResult<String> dr = new DeferredResult<String>();
ListenableFuture<ResponseEntity<String>> f1 = rt.getForEntity(URL1, String.class, "h" + idx);
f1.addCallback(s -> {
ListenableFuture<ResponseEntity<String>> f2 = rt.getForEntity(URL2, String.class, s.getBody());
f2.addCallback(s2 -> {
ListenableFuture<String> f3 = myService.work(s2.getBody());
f3.addCallback(s3 -> {
dr.setResult(s3);
}, e3 -> {
dr.setErrorResult(e3.getMessage());
});
}, e2 -> {
dr.setErrorResult(e2.getMessage());
});
}, e -> {
dr.setErrorResult(e.getMessage());
});
return dr;
}
示例5: createRequest
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
/**
* Method to create http requests to services
*/
public default <I, O> ListenableFuture<ResponseEntity<O>> createRequest(final URIBuilder uri,
final HttpMethod method, final I body, final Class<O> returnClazz, final HttpHeaders header) {
final AsyncRestTemplate restTemplate = new AsyncRestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
if (header != null) {
header.setContentType(MediaType.APPLICATION_JSON);
}
HttpEntity<?> entity;
if (body != null) {
entity = new HttpEntity<I>(body, header);
} else {
entity = new HttpEntity<String>(null, header);
}
return restTemplate.exchange(uri.toString(), method, entity, returnClazz);
}
示例6: getProcessState
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Async
public Future<ProcessStateDTO> getProcessState(final Long piId) throws URISyntaxException {
final CompletableFuture<ProcessStateDTO> future = new CompletableFuture<>();
final URIBuilder uri =
new URIBuilder(gatewayConfig.getProcessEngineAddress()).setPath("processes/state/" + piId);
final ListenableFuture<ResponseEntity<ProcessStateDTO>> responseFuture =
createRequest(uri, HttpMethod.GET, null, ProcessStateDTO.class, null);
responseFuture.addCallback(result -> {
final List<UserContainer> container = Lists.newArrayList(result.getBody().getSubjects());
getUser(container);
future.complete(result.getBody());
}, error -> {
future.completeExceptionally(error);
});
return future;
}
示例7: getProcessesInfoOfState
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Async
public Future<List<ProcessInfoDTO>> getProcessesInfoOfState(final String state, final int page,
final int size) throws URISyntaxException {
final CompletableFuture<List<ProcessInfoDTO>> future = new CompletableFuture<>();
final URIBuilder uri =
new URIBuilder(gatewayConfig.getProcessEngineAddress()).setPath("processes/" + state)
.addParameter("page", String.valueOf(page)).addParameter("size", String.valueOf(size));
final ListenableFuture<ResponseEntity<ProcessInfoDTO[]>> responseFuture =
createRequest(uri, HttpMethod.GET, null, ProcessInfoDTO[].class, null);
appendUserInformation(responseFuture, future);
return future;
}
示例8: send
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
public void send(String topic, String data) {
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, data);
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
logger.info("Success on sending message \"" + data + "\" to topic " + topic);
}
@Override
public void onFailure(Throwable ex) {
logger.error("Error on sending message \"" + data + "\", stacktrace " + ex.getMessage());
}
});
}
示例9: executeInternal
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(
final HttpHeaders headers, final byte[] bufferedOutput) throws IOException {
return this.taskExecutor.submitListenable(new Callable<ClientHttpResponse>() {
@Override
public ClientHttpResponse call() throws Exception {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
for (String headerValue : entry.getValue()) {
connection.addRequestProperty(headerName, headerValue);
}
}
if (connection.getDoOutput() && outputStreaming) {
connection.setFixedLengthStreamingMode(bufferedOutput.length);
}
connection.connect();
if (connection.getDoOutput()) {
FileCopyUtils.copy(bufferedOutput, connection.getOutputStream());
}
return new SimpleClientHttpResponse(connection);
}
});
}
示例10: userStatusReq
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
/**
* 查詢用戶在線狀態
*
* @param fromUserId 用戶ID
* @param userIdList 查詢列表
* @return
* @since 1.0
*/
@Async
public ListenableFuture<List<IMBaseDefine.UserStat>> userStatusReq(Long fromUserId, List<Long> userIdList) {
logger.debug("查詢用戶在線狀態, user_cnt={}", userIdList.size());
List<IMBaseDefine.UserStat> userStatList = new ArrayList<>();
for (Long userId: userIdList) {
UserClientInfoManager.UserClientInfo userClientInfo = userClientInfoManager.getUserInfo(userId);
IMBaseDefine.UserStat.Builder userStatBuiler = IMBaseDefine.UserStat.newBuilder();
userStatBuiler.setUserId(userId);
if (userClientInfo != null) {
userStatBuiler.setStatus(userClientInfo.getStatus());
} else {
userStatBuiler.setStatus(IMBaseDefine.UserStatType.USER_STATUS_OFFLINE);
}
userStatList.add(userStatBuiler.build());
}
AsyncResult<List<IMBaseDefine.UserStat>> result = new AsyncResult<>(userStatList);
return result;
}
示例11: testSend_onFailure
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Test
public void testSend_onFailure() {
ListenableFuture<String> future =
this.pubSubTemplate.publish("testTopic", this.pubsubMessage);
this.settableApiFuture.setException(new Exception("future failed."));
try {
future.get();
fail("Test should fail.");
}
catch (InterruptedException ie) {
fail("get() should fail with an ExecutionException.");
}
catch (ExecutionException ee) {
assertEquals("future failed.", ee.getCause().getMessage());
}
}
示例12: doExecute
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
/**
* Execute the given method on the provided URI. The
* {@link org.springframework.http.client.ClientHttpRequest}
* is processed using the {@link RequestCallback}; the response with
* the {@link ResponseExtractor}.
* @param url the fully-expanded URL to connect to
* @param method the HTTP method to execute (GET, POST, etc.)
* @param requestCallback object that prepares the request (can be {@code null})
* @param responseExtractor object that extracts the return value from the response (can
* be {@code null})
* @return an arbitrary object, as returned by the {@link ResponseExtractor}
*/
protected <T> ListenableFuture<T> doExecute(URI url, HttpMethod method, AsyncRequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
try {
AsyncClientHttpRequest request = createAsyncRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
ListenableFuture<ClientHttpResponse> responseFuture = request.executeAsync();
return new ResponseExtractorFuture<T>(method, url, responseFuture,
responseExtractor);
}
catch (IOException ex) {
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + url + "\":" + ex.getMessage(), ex);
}
}
示例13: send
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
public DeferredResult<LoginDetails> send(String content) {
System.out.println("send request");
final DeferredResult<LoginDetails> response = new DeferredResult<>();
ListenableFuture<LoginDetails> future = asyncRabbitTemplate.convertSendAndReceive(requestQueue.getName(),
content);
future.addCallback(new LoginHandlerResponse(response));
System.out.println(asyncRabbitTemplate.isAutoStartup());
System.out.println(asyncRabbitTemplate.isRunning());
return response;
}
示例14: send
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
public DeferredResult<LoginDetails> send(String content) {
System.out.println("send request");
final DeferredResult<LoginDetails> response = new DeferredResult<>();
ListenableFuture<LoginDetails> future =
asyncRabbitTemplate.convertSendAndReceive(exchange.getName(), "packt.async", content);
future.addCallback(new LoginHandlerResponse(response));
System.out.println(asyncRabbitTemplate.isAutoStartup());
System.out.println(asyncRabbitTemplate.isRunning());
return response;
}
示例15: userStatusReq
import org.springframework.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
public void userStatusReq(IMHeader header, MessageLite body, ChannelHandlerContext ctx) {
// CID_BUDDY_LIST_USERS_STATUS_REQUEST
logger.debug("Send the users status request to router");
long userId = super.getUserId(ctx);
IMUsersStatReq usersStatReq = (IMUsersStatReq) body;
ListenableFuture<List<IMBaseDefine.UserStat>> userStatFuture =
messageServerCluster.userStatusReq(userId, usersStatReq.getUserIdListList());
userStatFuture.addCallback((List<IMBaseDefine.UserStat> userStatList) -> {
// 查詢用戶狀態後處理
IMBuddy.IMUsersStatRsp.Builder userStatRes = IMBuddy.IMUsersStatRsp.newBuilder();
userStatRes.addAllUserStatList(userStatList);
userStatRes.setUserId(userId);
userStatRes.setAttachData(usersStatReq.getAttachData());
IMHeader headerRes = header.clone();
headerRes.setCommandId(
(short) BuddyListCmdID.CID_BUDDY_LIST_USERS_STATUS_RESPONSE_VALUE);
ctx.writeAndFlush(new IMProtoMessage<>(headerRes, userStatRes.build()));
}, (Throwable e) -> {
// 異常處理
logger.warn("處理推送異常", e);
});
}