dubbo上下文信息
- 上下文中存放的是当前调用过程中所需的环境信息。
- 所有配置信息都将转换为URL参数。
注意
RpcContext是一个ThreadLocal的临时状态记录器,当接收到RPC请求或发起RPC请求时,RpcContext的状态都会变化。
比如:A调用B,B再调用C。在B调用C之前,A调用了B,那么RpcContext中记录的是A调用B的信息;在B调用C之后,RpcContext记录的是B调用C的信息。
举个栗子
<!-- dubboC.xml -->
<!-- C 提供服务 -->
<bean id="demoCService" class="com.c.DemoCServiceImpl"/>
<dubbo:service interface="com.c.DemoCService" ref="demoCService" />
<!-- dubboB.xml -->
<!-- B消费C -->
<dubbo:reference id="demoCService" interface="com.c.DemoCService" />
<bean id="BBean" class="com.B.BServiceImpl">
<property id="demoCService" ref="demoCService" />
</bean>
<!-- B 提供服务 -->
<bean id="demoBService" class="com.B.DemoBServiceImpl" />
<dubbo:service interface="com.B.DemoBService" ref="demoBService" />
<!-- dubboA.xml -->
<!-- A消费B -->
<dubbo:reference id="demoBService" interface="com.B.DemoBService" />
<bean id="ABean" class="com.A.AServiceImpl">
<property id="demoBService" ref="demoBService"/>
<bean/>
配置好服务提供方和服务消费方的dubbo之后,来看服务提供方和服务消费方如何获取dubbo上下文信息:
Class A
//服务消费方
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:dubboA.xml");
DemoBService demoBService = (DemoBService)context.getBean("demoBService");
//远程调用
demoBService.xxx();
//本端是否为消费端
boolean isConsumerSide = RpcContext.getContext().isConsumerSide();
//获取最后一次调用的提供方IP地址
String serverIP = RpcContext.getContext().getRemoteHost();
//获取当前服务配置信息,所有配置信息都将转换为URL参数
String application = RpcContext.getContext().getUrl().getParameter("application");
//...
//注意,每次发起新的RPC调用,上下文信息都会变化
demoBService.yyy();
//...
Class B
//服务提供方
public class DemoBServiceImpl implements DemoBService {
public void xxx() {
//查看本端是否为服务提供方
boolean isProviderSide = RpcContext.getContext().isProviderSide();
//获取调用方的IP地址
String consumerIP = RpcContext.getContext().getRemoteHost();
//获取当前服务配置信息,所有配置信息都将转换为URL参数
String application = RpcContext.getContext().getUrl().getParamter("application");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:dubboB.xml");
DemoCService demoCService = (DemoCService)context.getBean("demoCService");
//远程调用C提供的服务(此次调用之后,此上下文信息从服务的提供者变为了服务的消费者)
demoCService.yyy();
//判断本端是否为消费端
boolean isConsumerSide = RpcContext.getContext().isConsumerSide();
//获取最后一次调用的提供方IP地址
String provideIP = RpcContext.getContext().getRemoteHost();
//获取当前服务配置信息,所有配置信息都将转换为URL的参数
String application = RpcContext.getContext().getUrl().getParamter("application");
}
}
Class C
public Class C {
public void yyy() {
//判断本端是否为服务端
boolean isProviderSide = RpcContext.getContext().isProviderSide();
//获取调用方的IP地址
String consumer = RpcContext.getContext().getRemoteHost();
//获取当前服务的配置信息
String application = RpcContext.getContext().getUrl.getParamter("application");
}
}