dubbo(4) 消费者订阅和消费服务

1 项目结构

 
2  maven依赖
  

3 applicationcontext.xml
<!-- 采用注释的方式配置bean -->
<context:annotation-config />

<!-- 配置要扫描的包 -->
<context:component-scan base-package="com.chy.service" />

<!-- proxy-target-class默认"false",更改为"ture"使用CGLib动态代理 -->
<aop:aspectj-autoproxy proxy-target-class="true" />

<import resource="dubbo-consumer.xml" />
4 dubbo-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://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

<!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="dubbo-consumer-one" />

<!-- 使用zookeeper注册中心暴露服务地址 -->
<!-- 注册中心地址 -->
<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181" />

<!-- 用户服务接口,和服务类名对应 -->
<dubbo:reference interface="com.chy.service.HelloService" id="helloService" />

</beans>
5 订阅接口
订阅的接口和服务发布的接口一致
package com.chy.service;

/**
* Created by chy on 2017/12/8.
*/
public interface HelloService {

String sayHello(String str);

}
6 程序入口
package com.chy;

import com.chy.service.HelloService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Hello world!
*
*/
public class App
{
private static ClassPathXmlApplicationContext context;

public static void main( String[] args ) throws IOException
{
context = new ClassPathXmlApplicationContext("applicationcontext.xml");
System.out.println(context.getDisplayName() + ": here");
context.start();
System.out.println("dubbo客户端端读取数据开始...");
new Thread(new Runnable() {
@Override
public void run() {
HelloService demoService = (HelloService) context.getBean("helloService");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while (true) {
try {
System.out.println(demoService.sayHello(format.format(new Date())));
Thread.sleep(2000);
}
catch (Exception ex){
System.out.println(ex.toString());
}
}
}
}).start();
System.out.println("dubbo客户端读取数据结束...");
System.in.read();
}
}
7 启动效果



 服务注册了2个进行消费均衡负载
 

猜你喜欢

转载自blog.csdn.net/chy2z/article/details/80463207