use of com.alibaba.nacos.consistency.entity.Response in project nacos by alibaba.
the class DistributedDatabaseOperateImpl method queryOne.
@Override
public <R> R queryOne(String sql, Object[] args, RowMapper<R> mapper) {
try {
LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "queryOne info : sql : {}, args : {}", sql, args);
byte[] data = serializer.serialize(SelectRequest.builder().queryType(QueryType.QUERY_ONE_WITH_MAPPER_WITH_ARGS).sql(sql).args(args).className(mapper.getClass().getCanonicalName()).build());
final boolean blockRead = EmbeddedStorageContextUtils.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(), ClassUtils.resolveGenericTypeByInterface(mapper.getClass()));
}
throw new NJdbcException(response.getErrMsg(), response.getErrMsg());
} catch (Exception e) {
LogUtil.FATAL_LOG.error("An exception occurred during the query operation : {}", e.toString());
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e.toString());
}
}
use of com.alibaba.nacos.consistency.entity.Response in project nacos by alibaba.
the class DistributedDatabaseOperateImpl method update.
@Override
public Boolean update(List<ModifyRequest> sqlContext, BiConsumer<Boolean, Throwable> consumer) {
try {
// Since the SQL parameter is Object[], in order to ensure that the types of
// array elements are not lost, the serialization here is done using the java-specific
// serialization framework, rather than continuing with the protobuff
LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "modifyRequests info : {}", sqlContext);
// {timestamp}-{group}-{ip:port}-{signature}
final String key = System.currentTimeMillis() + "-" + group() + "-" + memberManager.getSelf().getAddress() + "-" + MD5Utils.md5Hex(sqlContext.toString(), Constants.ENCODE);
WriteRequest request = WriteRequest.newBuilder().setGroup(group()).setKey(key).setData(ByteString.copyFrom(serializer.serialize(sqlContext))).putAllExtendInfo(EmbeddedStorageContextUtils.getCurrentExtendInfo()).setType(sqlContext.getClass().getCanonicalName()).build();
if (Objects.isNull(consumer)) {
Response response = this.protocol.write(request);
if (response.getSuccess()) {
return true;
}
LogUtil.DEFAULT_LOG.error("execute sql modify operation failed : {}", response.getErrMsg());
return false;
} else {
this.protocol.writeAsync(request).whenComplete((BiConsumer<Response, Throwable>) (response, ex) -> {
String errMsg = Objects.isNull(ex) ? response.getErrMsg() : ExceptionUtil.getCause(ex).getMessage();
consumer.accept(response.getSuccess(), StringUtils.isBlank(errMsg) ? null : new NJdbcException(errMsg));
});
}
return true;
} catch (TimeoutException e) {
LogUtil.FATAL_LOG.error("An timeout exception occurred during the update operation");
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e.toString());
} catch (Throwable e) {
LogUtil.FATAL_LOG.error("An exception occurred during the update operation : {}", e);
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e.toString());
}
}
use of com.alibaba.nacos.consistency.entity.Response in project nacos by alibaba.
the class DistributedDatabaseOperateImpl method dataImport.
@Override
public CompletableFuture<RestResult<String>> dataImport(File file) {
return CompletableFuture.supplyAsync(() -> {
try (DiskUtils.LineIterator iterator = DiskUtils.lineIterator(file)) {
int batchSize = 1000;
List<String> batchUpdate = new ArrayList<>(batchSize);
List<CompletableFuture<Response>> futures = new ArrayList<>();
while (iterator.hasNext()) {
String sql = iterator.next();
if (StringUtils.isNotBlank(sql)) {
batchUpdate.add(sql);
}
boolean submit = batchUpdate.size() == batchSize || !iterator.hasNext();
if (submit) {
List<ModifyRequest> requests = batchUpdate.stream().map(ModifyRequest::new).collect(Collectors.toList());
CompletableFuture<Response> future = protocol.writeAsync(WriteRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(serializer.serialize(requests))).putExtendInfo(DATA_IMPORT_KEY, Boolean.TRUE.toString()).build());
futures.add(future);
batchUpdate.clear();
}
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
for (CompletableFuture<Response> future : futures) {
Response response = future.get();
if (!response.getSuccess()) {
return RestResultUtils.failed(response.getErrMsg());
}
}
return RestResultUtils.success();
} catch (Throwable ex) {
LogUtil.DEFAULT_LOG.error("data import has error :", ex);
return RestResultUtils.failed(ex.getMessage());
}
});
}
use of com.alibaba.nacos.consistency.entity.Response in project nacos by alibaba.
the class DistributedDatabaseOperateImpl method queryMany.
@Override
public <R> List<R> queryMany(String sql, Object[] args, RowMapper<R> mapper) {
try {
LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "queryMany info : sql : {}, args : {}", sql, args);
byte[] data = serializer.serialize(SelectRequest.builder().queryType(QueryType.QUERY_MANY_WITH_MAPPER_WITH_ARGS).sql(sql).args(args).className(mapper.getClass().getCanonicalName()).build());
final boolean blockRead = EmbeddedStorageContextUtils.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(), List.class);
}
throw new NJdbcException(response.getErrMsg());
} catch (Exception e) {
LogUtil.FATAL_LOG.error("An exception occurred during the query operation : {}", e.toString());
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e.toString());
}
}
use of com.alibaba.nacos.consistency.entity.Response in project nacos by alibaba.
the class NacosStateMachine method onApply.
@Override
public void onApply(Iterator iter) {
int index = 0;
int applied = 0;
Message message;
NacosClosure closure = null;
try {
while (iter.hasNext()) {
Status status = Status.OK();
try {
if (iter.done() != null) {
closure = (NacosClosure) iter.done();
message = closure.getMessage();
} else {
final ByteBuffer data = iter.getData();
message = ProtoMessageUtil.parse(data.array());
if (message instanceof ReadRequest) {
// 'iter.done() == null' means current node is follower, ignore read operation
applied++;
index++;
iter.next();
continue;
}
}
LoggerUtils.printIfDebugEnabled(Loggers.RAFT, "receive log : {}", message);
if (message instanceof WriteRequest) {
Response response = processor.onApply((WriteRequest) message);
postProcessor(response, closure);
}
if (message instanceof ReadRequest) {
Response response = processor.onRequest((ReadRequest) message);
postProcessor(response, closure);
}
} catch (Throwable e) {
index++;
status.setError(RaftError.UNKNOWN, e.toString());
Optional.ofNullable(closure).ifPresent(closure1 -> closure1.setThrowable(e));
throw e;
} finally {
Optional.ofNullable(closure).ifPresent(closure1 -> closure1.run(status));
}
applied++;
index++;
iter.next();
}
} catch (Throwable t) {
Loggers.RAFT.error("processor : {}, stateMachine meet critical error: {}.", processor, t);
iter.setErrorAndRollback(index - applied, new Status(RaftError.ESTATEMACHINE, "StateMachine meet critical error: %s.", ExceptionUtil.getStackTrace(t)));
}
}
Aggregations