下面列出了怎么用com.alibaba.dubbo.rpc.RpcContext的API类实例代码及写法,或者点击链接到github查看源代码。
TestServer(Propagation.Factory propagationFactory) {
extractor = propagationFactory.get().extractor(Map::get);
linkLocalIp = Platform.get().linkLocalIp();
if (linkLocalIp != null) {
// avoid dubbo's logic which might pick docker ip
System.setProperty(Constants.DUBBO_IP_TO_BIND, linkLocalIp);
System.setProperty(Constants.DUBBO_IP_TO_REGISTRY, linkLocalIp);
}
service = new ServiceConfig<>();
service.setApplication(new ApplicationConfig("bean-provider"));
service.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
service.setProtocol(new ProtocolConfig("dubbo", PickUnusedPort.get()));
service.setInterface(GreeterService.class);
service.setRef((method, parameterTypes, args) -> {
requestQueue.add(extractor.extract(RpcContext.getContext().getAttachments()));
return args[0];
});
}
@SuppressWarnings("unchecked")
@Test
public void testRpcException() {
Logger logger = EasyMock.createMock(Logger.class);
RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234);
RpcException exception = new RpcException("TestRpcException");
logger.error(EasyMock.eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), EasyMock.eq(exception));
ExceptionFilter exceptionFilter = new ExceptionFilter(logger);
RpcInvocation invocation = new RpcInvocation("sayHello", new Class<?>[]{String.class}, new Object[]{"world"});
Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class);
EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception);
EasyMock.replay(logger, invoker);
try {
exceptionFilter.invoke(invoker, invocation);
} catch (RpcException e) {
assertEquals("TestRpcException", e.getMessage());
}
EasyMock.verify(logger, invoker);
RpcContext.removeContext();
}
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) {
RpcContext context = RpcContext.getContext(); // 提供方必须在invoke()之前获取context信息
long start = System.currentTimeMillis(); // 记录起始时间戮
getConcurrent(invoker, invocation).incrementAndGet(); // 并发计数
try {
Result result = invoker.invoke(invocation); // 让调用链往下执行
collect(invoker, invocation, result, context, start, false);
return result;
} catch (RpcException e) {
collect(invoker, invocation, null, context, start, true);
throw e;
} finally {
getConcurrent(invoker, invocation).decrementAndGet(); // 并发计数
}
} else {
return invoker.invoke(invocation);
}
}
@Test
public void testFilter() throws Exception {
MonitorFilter monitorFilter = new MonitorFilter();
monitorFilter.setMonitorFactory(monitorFactory);
Invocation invocation = new RpcInvocation("aaa", new Class<?>[0], new Object[0]);
RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
monitorFilter.invoke(serviceInvoker, invocation);
while (lastStatistics == null) {
Thread.sleep(10);
}
Assert.assertEquals("abc", lastStatistics.getParameter(MonitorService.APPLICATION));
Assert.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(MonitorService.INTERFACE));
Assert.assertEquals("aaa", lastStatistics.getParameter(MonitorService.METHOD));
Assert.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(MonitorService.PROVIDER));
Assert.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress());
Assert.assertEquals(null, lastStatistics.getParameter(MonitorService.CONSUMER));
Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.SUCCESS, 0));
Assert.assertEquals(0, lastStatistics.getParameter(MonitorService.FAILURE, 0));
Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.CONCURRENT, 0));
Assert.assertEquals(invocation, lastInvocation);
}
public Result providerInvoke(Invoker<?> invoker, Invocation invocation) throws RpcException, RemotingException {
String interfaceClazz = RpcContext.getContext().getUrl().getServiceInterface();
boolean participantFlag = TransactionParticipant.class.getName().equals(interfaceClazz);
boolean xaResourceFlag = XAResource.class.getName().equals(interfaceClazz);
boolean coordinatorFlag = RemoteCoordinator.class.getName().equals(interfaceClazz);
if (participantFlag == false && xaResourceFlag == false && coordinatorFlag == false) {
return this.providerInvokeForSVC(invoker, invocation);
} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_RESOURCE_START)) {
return this.providerInvokeForKey(invoker, invocation);
} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_IDENTIFIER)) {
return this.providerInvokeForKey(invoker, invocation);
} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_APPLICATION)) {
return this.providerInvokeForKey(invoker, invocation);
} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_REMOTEADDR)) {
return this.providerInvokeForKey(invoker, invocation);
} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_REMOTENODE)) {
return this.providerInvokeForKey(invoker, invocation);
} else {
return this.providerInvokeForTCC(invoker, invocation);
}
}
@Test
public void testGenericInvokeWithRpcContext() {
RpcContext.getContext().setAttachment("myContext", "123");
HessianServiceImpl server = new HessianServiceImpl();
ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
URL url = URL.valueOf("hessian://127.0.0.1:5342/" + HessianService.class.getName() + "?version=1.0.0");
Exporter<HessianService> exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url));
Invoker<GenericService> invoker = protocol.refer(GenericService.class, url);
GenericService client = proxyFactory.getProxy(invoker, true);
String result = (String) client.$invoke("context", new String[]{"java.lang.String"}, new Object[]{"haha"});
Assert.assertEquals("Hello, haha context, 123", result);
invoker.destroy();
exporter.unexport();
}
@SuppressWarnings("unchecked")
@Test
public void testSetContext() {
invocation = EasyMock.createMock(Invocation.class);
EasyMock.expect(invocation.getMethodName()).andReturn("$enumlength").anyTimes();
EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Enum.class }).anyTimes();
EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes();
EasyMock.replay(invocation);
invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
RpcResult result = new RpcResult();
result.setValue("High");
EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
EasyMock.replay(invoker);
contextFilter.invoke(invoker, invocation);
assertNull(RpcContext.getContext().getInvoker());
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
RpcContext.getContext()
.setInvoker(invoker)
.setInvocation(invocation)
.setLocalAddress(NetUtils.getLocalHost(), 0)
.setRemoteAddress(invoker.getUrl().getHost(),
invoker.getUrl().getPort());
if (invocation instanceof RpcInvocation) {
((RpcInvocation) invocation).setInvoker(invoker);
}
try {
// com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper.buildInvokerChain com.alibaba.dubbo.rpc.Invoker.invoke()
RpcResult result = (RpcResult) invoker.invoke(invocation);
RpcContext.getServerContext().setAttachments(result.getAttachments());
return result;
} finally {
RpcContext.getContext().clearAttachments();
}
}
public static void main(String[] args) throws Exception {
String config = AsyncConsumer.class.getPackage().getName().replace('.', '/') + "/async-consumer.xml";
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
context.start();
final AsyncService asyncService = (AsyncService)context.getBean("asyncService");
Future<String> f = RpcContext.getContext().asyncCall(new Callable<String>() {
public String call() throws Exception {
return asyncService.sayHello("async call request");
}
});
System.out.println("async call ret :" + f.get());
RpcContext.getContext().asyncCall(new Runnable() {
public void run() {
asyncService.sayHello("oneway call request1");
asyncService.sayHello("oneway call request2");
}
});
System.in.read();
}
@Test
public void test_Async_Future_Multi() throws Exception {
initOrResetUrl(true);
destroyService();
exportService();
referService();
int requestId1 = 1;
Person ret = demoProxy.get(requestId1);
Assert.assertEquals(null, ret);
Future<Person> p1Future = RpcContext.getContext().getFuture();
int requestId2 = 1;
Person ret2 = demoProxy.get(requestId2);
Assert.assertEquals(null, ret2);
Future<Person> p2Future = RpcContext.getContext().getFuture();
ret = p1Future.get(1000, TimeUnit.MICROSECONDS);
ret2 = p2Future.get(1000, TimeUnit.MICROSECONDS);
Assert.assertEquals(requestId1, ret.getId());
Assert.assertEquals(requestId2, ret.getId());
destroyService();
}
public void subscribe(URL url, NotifyListener listener) {
if (getUrl().getPort() == 0) {
URL registryUrl = RpcContext.getContext().getUrl();
if (registryUrl != null && registryUrl.getPort() > 0
&& RegistryService.class.getName().equals(registryUrl.getPath())) {
super.setUrl(registryUrl);
super.register(registryUrl);
}
}
String client = RpcContext.getContext().getRemoteAddressString();
ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
if (clientListeners == null) {
remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
clientListeners = remoteSubscribed.get(client);
}
Set<NotifyListener> listeners = clientListeners.get(url);
if (listeners == null) {
clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
listeners = clientListeners.get(url);
}
listeners.add(listener);
super.subscribe(url, listener);
subscribed(url, listener);
}
public void subscribe(URL url, NotifyListener listener) {
if (getUrl().getPort() == 0) {
URL registryUrl = RpcContext.getContext().getUrl();
if (registryUrl != null && registryUrl.getPort() > 0
&& RegistryService.class.getName().equals(registryUrl.getPath())) {
super.setUrl(registryUrl);
super.register(registryUrl);
}
}
String client = RpcContext.getContext().getRemoteAddressString();
ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
if (clientListeners == null) {
remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
clientListeners = remoteSubscribed.get(client);
}
Set<NotifyListener> listeners = clientListeners.get(url);
if (listeners == null) {
clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
listeners = clientListeners.get(url);
}
listeners.add(listener);
super.subscribe(url, listener);
subscribed(url, listener);
}
public void subscribe(URL url, NotifyListener listener) {
if (getUrl().getPort() == 0) {
URL registryUrl = RpcContext.getContext().getUrl();
if (registryUrl != null && registryUrl.getPort() > 0
&& RegistryService.class.getName().equals(registryUrl.getPath())) {
super.setUrl(registryUrl);
super.register(registryUrl);
}
}
String client = RpcContext.getContext().getRemoteAddressString();
ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
if (clientListeners == null) {
remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
clientListeners = remoteSubscribed.get(client);
}
Set<NotifyListener> listeners = clientListeners.get(url);
if (listeners == null) {
clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
listeners = clientListeners.get(url);
}
listeners.add(listener);
super.subscribe(url, listener);
subscribed(url, listener);
}
@Test
public void test_Async_Future_Multi() throws Exception {
initOrResetUrl(true);
destroyService();
exportService();
referService();
int requestId1 = 1;
Person ret = demoProxy.get(requestId1);
Assert.assertEquals(null, ret);
Future<Person> p1Future = RpcContext.getContext().getFuture();
int requestId2 = 1;
Person ret2 = demoProxy.get(requestId2);
Assert.assertEquals(null, ret2);
Future<Person> p2Future = RpcContext.getContext().getFuture();
ret = p1Future.get(1000, TimeUnit.MICROSECONDS);
ret2 = p2Future.get(1000, TimeUnit.MICROSECONDS);
Assert.assertEquals(requestId1, ret.getId());
Assert.assertEquals(requestId2, ret.getId());
destroyService();
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dubbo-consumer.xml");
context.start();
DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理
// System.out.println(demoService.syncSayHello("world"));
System.out.println(demoService.asyncSayHello("world"));
Future<String> futrue = RpcContext.getContext().getFuture();
System.out.println(futrue.get());
// System.out.println(demoService.sayHello(new TestBean("zhaohui", 99,
// "nanjing")));
// Map<String, String> map = (Map<String, String>)
// context.getBean("redis");
// map.put("haha", "vvv1");
//
// System.out.println(map.get("haha"));
}
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
RpcContext.getContext()
.setInvoker(invoker)
.setInvocation(invocation)
.setLocalAddress(NetUtils.getLocalHost(), 0)
.setRemoteAddress(invoker.getUrl().getHost(),
invoker.getUrl().getPort());
if (invocation instanceof RpcInvocation) {
((RpcInvocation)invocation).setInvoker(invoker);
}
try {
return invoker.invoke(invocation);
} finally {
RpcContext.getContext().clearAttachments();
}
}
/**
* set rpc client span tags
* @param invoker
* @param sofaTracerSpan
*/
private void appendRpcClientSpanTags(Invoker<?> invoker, SofaTracerSpan sofaTracerSpan) {
if (sofaTracerSpan == null) {
return;
}
RpcContext rpcContext = RpcContext.getContext();
Map<String, String> tagsStr = sofaTracerSpan.getTagsWithStr();
tagsStr.put(Tags.SPAN_KIND.getKey(), spanKind(rpcContext));
String protocol = rpcContext.getUrl().getProtocol();
tagsStr.put(CommonSpanTags.PROTOCOL, protocol == null ? BLANK : protocol);
String service = invoker.getInterface().getName();
tagsStr.put(CommonSpanTags.SERVICE, service == null ? BLANK : service);
String methodName = rpcContext.getMethodName();
tagsStr.put(CommonSpanTags.METHOD, methodName == null ? BLANK : methodName);
tagsStr.put(CommonSpanTags.CURRENT_THREAD_NAME, Thread.currentThread().getName());
String app = rpcContext.getUrl().getParameter(Constants.APPLICATION_KEY);
tagsStr.put(CommonSpanTags.LOCAL_APP, app == null ? BLANK : app);
tagsStr.put(CommonSpanTags.REMOTE_HOST, rpcContext.getRemoteHost());
tagsStr.put(CommonSpanTags.REMOTE_PORT, String.valueOf(rpcContext.getRemotePort()));
tagsStr.put(CommonSpanTags.LOCAL_HOST, rpcContext.getLocalHost());
}
@Override
public Object reply( ExchangeChannel channel, Object msg ) throws RemotingException {
if ( msg instanceof Invocation ) {
Invocation inv = ( Invocation ) msg;
String serviceName = inv.getAttachments().get(Constants.INTERFACE_KEY);
String serviceKey = serviceKey( channel.getLocalAddress().getPort(),
serviceName, null, null );
DubboExporter<?> exporter = (DubboExporter<?>) exporterMap.get( serviceKey );
if (exporter == null) {
throw new RemotingException(channel,
"Not found exported service: "
+ serviceKey
+ " in "
+ exporterMap.keySet()
+ ", may be version or group mismatch "
+ ", channel: consumer: "
+ channel.getRemoteAddress()
+ " --> provider: "
+ channel.getLocalAddress()
+ ", message:"+ msg);
}
RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress());
return exporter.getInvoker().invoke( inv );
}
throw new RemotingException(channel,
"Unsupported request: "
+ (msg.getClass().getName() + ": " + msg)
+ ", channel: consumer: "
+ channel.getRemoteAddress()
+ " --> provider: "
+ channel.getLocalAddress());
}
@Test
public void testSetContext(){
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
Invoker<DemoService> invoker = new MyInvoker<DemoService>(url);
Invocation invocation = new MockInvocation();
consumerContextFilter.invoke(invoker, invocation);
assertEquals(invoker,RpcContext.getContext().getInvoker());
assertEquals(invocation,RpcContext.getContext().getInvocation());
assertEquals(NetUtils.getLocalHost() + ":0",RpcContext.getContext().getLocalAddressString());
assertEquals("test:11",RpcContext.getContext().getRemoteAddressString());
}
@Test
public void testInvokeExceptoin() {
resetInvokerToException();
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<FailbackClusterInvokerTest>(
dic);
invoker.invoke(invocation);
Assert.assertNull(RpcContext.getContext().getInvoker());
}
@Test
public void testSetContext(){
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
Invoker<DemoService> invoker = new MyInvoker<DemoService>(url);
Invocation invocation = new MockInvocation();
consumerContextFilter.invoke(invoker, invocation);
assertEquals(invoker,RpcContext.getContext().getInvoker());
assertEquals(invocation,RpcContext.getContext().getInvocation());
assertEquals(NetUtils.getLocalHost() + ":0",RpcContext.getContext().getLocalAddressString());
assertEquals("test:11",RpcContext.getContext().getRemoteAddressString());
}
public void handle(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String uri = request.getRequestURI();
HessianSkeleton skeleton = skeletonMap.get(uri);
if (! request.getMethod().equalsIgnoreCase("POST")) {
response.setStatus(500);
} else {
RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
try {
skeleton.invoke(request.getInputStream(), response.getOutputStream());
} catch (Throwable e) {
throw new ServletException(e);
}
}
}
@GET
@Path("{id : \\d+}")
public User getUser(@PathParam("id") Long id/*, @Context HttpServletRequest request*/) {
// test context injection
// System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : ""));
// System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString());
if (RpcContext.getContext().getRequest(HttpServletRequest.class) != null) {
System.out.println("Client IP address from RpcContext: " + RpcContext.getContext().getRequest(HttpServletRequest.class).getRemoteAddr());
}
if (RpcContext.getContext().getResponse(HttpServletResponse.class) != null) {
System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse(HttpServletResponse.class));
}
return userService.getUser(id);
}
public void handle(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String uri = request.getRequestURI();
HttpInvokerServiceExporter skeleton = skeletonMap.get(uri);
if (! request.getMethod().equalsIgnoreCase("POST")) {
response.setStatus(500);
} else {
RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
try {
skeleton.handleRequest(request, response);
} catch (Throwable e) {
throw new ServletException(e);
}
}
}
public void handle(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String uri = request.getRequestURI();
HttpInvokerServiceExporter skeleton = skeletonMap.get(uri);
if (! request.getMethod().equalsIgnoreCase("POST")) {
response.setStatus(500);
} else {
RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
try {
skeleton.handleRequest(request, response);
} catch (Throwable e) {
throw new ServletException(e);
}
}
}
public Result invoke(Invoker<?> invoker, Invocation inv)
throws RpcException {
String token = invoker.getUrl().getParameter(Constants.TOKEN_KEY);
if (ConfigUtils.isNotEmpty(token)) {
Class<?> serviceType = invoker.getInterface();
Map<String, String> attachments = inv.getAttachments();
String remoteToken = attachments == null ? null : attachments.get(Constants.TOKEN_KEY);
if (! token.equals(remoteToken)) {
throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + inv.getMethodName() + "() from consumer " + RpcContext.getContext().getRemoteHost() + " to provider " + RpcContext.getContext().getLocalHost());
}
}
return invoker.invoke(inv);
}
@Test
public void testInvokeApplicationKey() {
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(Invocation.class);
URL url = URL.valueOf("test://test:111/test?application=serviceA");
when(invoker.getUrl()).thenReturn(url);
filter.invoke(invoker, invocation);
verify(invoker).invoke(invocation);
String application = RpcContext.getContext().getAttachment(DubboUtils.DUBBO_APPLICATION_KEY);
assertEquals("serviceA", application);
}
@Test()
public void testRetryFailed() {
resetInvokerToException();
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<FailbackClusterInvokerTest>(
dic);
invoker.invoke(invocation);
Assert.assertNull(RpcContext.getContext().getInvoker());
invoker.retryFailed();// when retry the invoker which get from failed map already is not the mocked invoker,so
// it can be invoke successfully
}
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
try {
List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
Compilable compilable = (Compilable) engine;
Bindings bindings = engine.createBindings();
bindings.put("invokers", invokersCopy);
bindings.put("invocation", invocation);
bindings.put("context", RpcContext.getContext());
CompiledScript function = compilable.compile(rule);
Object obj = function.eval(bindings);
if (obj instanceof Invoker[]) {
invokersCopy = Arrays.asList((Invoker<T>[]) obj);
} else if (obj instanceof Object[]) {
invokersCopy = new ArrayList<Invoker<T>>();
for (Object inv : (Object[]) obj) {
invokersCopy.add((Invoker<T>)inv);
}
} else {
invokersCopy = (List<Invoker<T>>) obj;
}
return invokersCopy;
} catch (ScriptException e) {
//fail then ignore rule .invokers.
logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
return invokers;
}
}
@Override
public User getUser(@Min(value = 1L, message = "User ID must be greater than 1") @PathParam("id") Long id) {
// test context injection
// System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : ""));
// System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString());
if (RpcContext.getContext().getRequest(HttpServletRequest.class) != null) {
System.out.println("Client IP address from RpcContext: " + RpcContext.getContext().getRequest(HttpServletRequest.class).getRemoteAddr());
}
if (RpcContext.getContext().getResponse(HttpServletResponse.class) != null) {
System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse(HttpServletResponse.class));
}
return userService.getUser(id);
}