1、接口及实现类定义超时时间
public interface HelloService {
String hello(String name,int timeToWait);
}
@Service
public class HelloServiceImpl implements HelloService {
@Override
public String hello(String name,int timeToWait) {
try {
Thread.sleep(timeToWait);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello" + name;
}
}
2、消费组配置 consumer.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://dubbo.apache.org/schema/dubbo
http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!--提供应用方信息,用于计算依赖关系-->
<dubbo:application name="service-consumer"/>
<!--使用zookeeper注册中心暴露服务地址-->
<dubbo:registry address="zookeeper://101.132.167.18:2181?timeout=30000"/>
<!--使用dubbo协议在20882端口暴露服务,也可以使用 rmi 协议暴露-->
<dubbo:reference id="helloService" interface="com.lagou.service.HelloService">
<dubbo:method name="hello" async="true"/>
</dubbo:reference>
</beans>
3、消费组启动类
public class XMLConsumerMain {
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("consumer.xml");
HelloService helloService = context.getBean(HelloService.class);
while (true){
System.in.read();
String hello = helloService.hello("world", 100);
//利用future模式来获取
Future<Object> future = RpcContext.getContext().getFuture();
System.out.println("result:" + hello);
System.out.println("future result:" + future.get());
}
}
}