我有多个服务,其中一些使用Hystrix的HystrixObservableCommand来调用其他服务,而其他服务使用HystrixCommand。如何将调用服务中的traceId传递给HystrixObservableCommand中的Observables,如果调用了回退函数,还可以传递它们吗?
所有服务都使用grpc-java。
我的示例代码:
WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
String messageFromWorldService = "";
String idFromWorldService = "";
try {
Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
messageFromWorldService = greeterReply.getMessage();
idFromWorldService = greeterReply.getId();
logger.info("Response from WorldService -- {}, id = {}", messageFromWorldService, idFromWorldService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
logger.warn("Exception when calling WorldService\n" + e);
}
WorldCommand.java
public class WorldCommand extends HystrixObservableCommand<Greeter.GreeterReply> {
private static final Logger logger = LoggerFactory.getLogger(WorldCommand.class.getName());
private final Greeter.GreeterRequest greeterRequest;
private final WorldServiceGrpc.WorldServiceStub worldServiceStub;
public WorldCommand(Greeter.GreeterRequest greeterRequest, WorldServiceGrpc.WorldServiceStub worldServiceStub) {
super(HystrixCommandGroupKey.Factory.asKey("WorldService"));
this.greeterRequest = greeterRequest;
this.worldServiceStub = worldServiceStub;
}
@Override
protected Observable<Greeter.GreeterReply> construct() {
Context context = Context.current();
return Observable.create(new Observable.OnSubscribe<Greeter.GreeterReply>() {
@Override
public void call(Subscriber<? super Greeter.GreeterReply> observer) {
logger.info("In WorldCommand");
if (!observer.isUnsubscribed()) {
//pass on the context, if you want only certain headers to pass on then create a new Context and attach it.
context.attach();
logger.info("In WorldCommand after attach");
worldServiceStub.greetWithHelloOrWorld(greeterRequest, new StreamObserver<Greeter.GreeterReply>() {
@Override
public void onNext(Greeter.GreeterReply greeterReply) {
logger.info("Response from WorldService -- {}, id = {}", greeterReply.getMessage(), greeterReply.getId());
observer.onNext(greeterReply);
observer.onCompleted();
}
@Override
public void onError(Throwable t) {
logger.info("Exception from WorldService -- {}", t);
}
@Override
public void onCompleted() {
}
});
}
}
} ).subscribeOn(Schedulers.io());
}
@Override
protected Observable<Greeter.GreeterReply> resumeWithFallback() {
logger.info("Response from fallback");
Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("teammate").setId("-1").build();
return Observable.just(greeterReply);
}
我正在使用Zipkin grpc跟踪和MDCCurrentTraceContext在日志中打印traceId和spanId。
WorldCommand中的两个日志条目都不打印trace和span id,它们在RxIoScheduler线程上调用。
编辑
根据Mike的建议添加了ConcurrencyStrategy。
public class CustomHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
private static final Logger log = LoggerFactory.getLogger(CustomHystrixConcurrencyStrategy.class);
public <T> Callable<T> wrapCallable(Callable<T> callable){
log.info("In CustomHystrixConcurrencyStrategy: callable="+ callable.toString());
return new ContextCallable<>(callable);
}
}
HelloService调用两个服务World和Team。 WorldCommand是HystrixObservableCommand,TeamCommand是HystrixCommand。
logger.info("In the HelloService:greetWithHelloWorld");
Greeter.GreeterRequest greeterRequest = Greeter.GreeterRequest.newBuilder().setId(request.getId()).build();
//Call WorldService
ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
//Async stub instead of blockingStub
WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);
WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
String messageFromWorldService = "";
String idFromWorldService = "";
try {
Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
messageFromWorldService = greeterReply.getMessage();
idFromWorldService = greeterReply.getId();
logger.info("Response from WorldService -- {}, id = {}", messageFromWorldService, idFromWorldService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
logger.warn("Exception when calling WorldService\n" + e);
}
//Call TeamService
ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);
String messageFromTeamService = "";
String idFromTeamService = "";
try {
Greeter.GreeterReply greeterReply = teamCommand.construct().toBlocking().toFuture().get();
messageFromTeamService = greeterReply.getMessage();
idFromTeamService = greeterReply.getId();
logger.info("Response from TeamService -- {}, id = {}", messageFromTeamService, idFromTeamService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
logger.warn("Exception when calling TeamService\n" + e);
}
assert(idFromWorldService.equals(idFromTeamService));
Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
responseObserver.onNext(greeterReply);
responseObserver.onCompleted();
PreservableContext类
public class PreservableContexts {
//private final TraceContext traceContext;
private static final Logger logger = LoggerFactory.getLogger(PreservableContexts.class.getName());
public PreservableContexts() {
logger.info("Creating new PreservableContexts");
//this.traceContext = TraceContextHolder.getContext();
}
public void set() {
// if (traceContext != null) {
//TraceContextHolder.setContext(traceContext);
// }
}
public void clear() {
//TraceContextHolder.clearContext();
}
永远不会打印PreservableContexts和CustomHystrixConcurrencyStrategy中的日志。我在启动HelloServer时注册了startegy。
HystrixConcurrencyStrategy strategy = new CustomHystrixConcurrencyStrategy();
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
context = HystrixRequestContext.initializeContext();
编辑2
更新了Observable的设置方式:
ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
//Async stub instead of blockingStub
WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);
WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
//Call TeamService
ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
TeamServiceGrpc.TeamServiceStub teamServiceStub = TeamServiceGrpc.newStub(teamChannel);
//TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);
try {
rx.Observable<Greeter.GreeterReply> worldReplyObservable = worldCommand.observe().subscribeOn(Schedulers.computation());
rx.Observable<Greeter.GreeterReply> teamReplyObservable = teamCommand.observe().subscribeOn(Schedulers.computation());
Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
@Override
public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
String messageFromWorldService = worldReply.getMessage();
String idFromWorldService = worldReply.getId();
logger.info("Response from WorldService -- {}, id = {}", messageFromWorldService, idFromWorldService);
String messageFromTeamService = teamReply.getMessage();
String idFromTeamService = teamReply.getId();
logger.info("Response from TeamService -- {}, id = {}", messageFromTeamService, idFromTeamService);
assert(idFromWorldService.equals(idFromTeamService));
Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
logger.info("Final response=" + greeterReply.getMessage());
responseObserver.onNext(greeterReply);
responseObserver.onCompleted();
return null;
}
});
} catch (StatusRuntimeException e) {
logger.warn("Exception when calling WorldService and/or TeamService\n" + e);
}
我现在有一个奇怪的问题,对TeamCommand和WorldCommand的调用没有完成,因为这段代码永远不会被执行:
Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
@Override
public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
String messageFromWorldService = worldReply.getMessage();
此外,如果存在回退,则hystrix-timer线程不再具有MDC。
答案 0 :(得分:0)
我对hysterix知之甚少,但是如果你试图传递一些像跟踪ID这样的上下文信息,那么io.grpc.Context就是要使用的正确类。您需要调用context.withValue
以使用traceID创建新上下文。在您想要数据的位置,您需要附加上下文。另外一定要在完成时分离上下文,我看不到你的代码片段。
答案 1 :(得分:0)
你需要使用......
HystrixPlugins.getInstance().registerConcurrencyStrategy(...)
...注册使用您自己的HystrixConcurrencyStrategy
...
Callable
public class ConcurrencyStrategy extends HystrixConcurrencyStrategy {
@Override
public <K> Callable<K> wrapCallable(Callable<K> c) {
return new ContextCallable<>(c);
}
}
......在电路周围应用环境保护...
public class ContextCallable<K> implements Callable<K> {
private final Callable<K> callable;
private final PreservableContexts contexts;
public ContextCallable(Callable<K> actual) {
this.callable = actual;
this.contexts = new PreservableContexts();
}
@Override
public K call() throws Exception {
contexts.set();
try {
return callable.call();
} finally {
contexts.clear();
}
}
}
... via是一个能够保留Zipkin上下文的辅助类......
public class PreservableContexts {
private final TraceContext traceContext;
public PreservableContexts() {
this.traceContext = TraceContextHolder.getContext();
}
public void set() {
if (traceContext != null) {
TraceContextHolder.setContext(traceContext);
}
}
public void clear() {
TraceContextHolder.clearContext();
}
}
...并允许一种简单的方法来添加您可能希望保留的其他上下文,例如MDC,SecurityContext等......