您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關dubbo中ConsumerContextFilter的作用是什么,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ConsumerContextFilter.java
@Activate(group = CONSUMER, order = -10000) public class ConsumerContextFilter extends ListenableFilter { public ConsumerContextFilter() { super.listener = new ConsumerContextListener(); } @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 { RpcContext.removeServerContext(); return invoker.invoke(invocation); } finally { RpcContext.removeContext(); } } static class ConsumerContextListener implements Listener { @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { RpcContext.getServerContext().setAttachments(appResponse.getAttachments()); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { } } }
ConsumerContextFilter繼承了ListenableFilter,其invoke方法在invoke之前會給RpcContext.getContext()設置invoker、invocation、localAddress、remoteAddress并移除serverContext;在invoke之后移除當前context;其listener為ConsumerContextListener,在onResponse的時候,會給RpcContext.getServerContext()設置attachments
dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ConsumerContextFilterTest.java
public class ConsumerContextFilterTest { Filter consumerContextFilter = new ConsumerContextFilter(); @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(); Result asyncResult = consumerContextFilter.invoke(invoker, invocation); asyncResult.thenApplyWithContext(result -> { assertEquals(invoker, RpcContext.getContext().getInvoker()); assertEquals(invocation, RpcContext.getContext().getInvocation()); assertEquals(NetUtils.getLocalHost() + ":0", RpcContext.getContext().getLocalAddressString()); assertEquals("test:11", RpcContext.getContext().getRemoteAddressString()); return result; }); } }
這里使用asyncResult.thenApplyWithContext來驗證一下RpcContext.getContext()的invoker、invocation、localhost、remoteAddress值
ConsumerContextFilter繼承了ListenableFilter,其invoke方法在invoke之前會給RpcContext.getContext()設置invoker、invocation、localAddress、remoteAddress并移除serverContext;在invoke之后移除當前context;其listener為ConsumerContextListener,在onResponse的時候,會給RpcContext.getServerContext()設置attachments
上述就是小編為大家分享的dubbo中ConsumerContextFilter的作用是什么了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。