Dubbo与Spring的配合使用

Dubbo是一个服务治理框架,对分布式服务的管理和治理、监控有较好的实现。

本案举例说明Dubbo与Spring的配合使用:

1.  Maven引入dubbo的配置

<dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>dubbo</artifactId>
                <version>2.5.3</version>
</dependency>

2.  增加Spring的Dubbo provider配置文件 spring-dubbo-provider.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管理页面比较清晰是哪个应用暴露出来的 -->
    <dubbo:application name="user_provider"/>
    <!-- 使用zookeeper注册中心注册服务 -->
    <dubbo:registry address="${zookeeper.registry}"/>

    <dubbo:protocol port="${dubbo.provider.port}"/>

    <dubbo:monitor protocol="registry"/>
    <!-- 暴露的服务接口 -->
    <dubbo:service interface="com.test.api.UserService"
                   ref="userService" timeout="5000" retries="2" />

    <bean id="userService" class="com.test.service.UserServiceImpl" />

</beans>

3. 接口和实现类代码:

UserService接口:

public interface UserService {
   public String hello(String name);
}

UserServiceImpl类:

public interface UserServiceImpl implement UserService {
   public String hello(String name){
        return "hello"+name;
   }
}

4. 消费方的配置文件

<?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="user_consumer" />

    <dubbo:registry address="${zookeeper.registry}"/>
    <dubbo:monitor protocol="registry"/>

    <!-- 注册中心配置 -->
    <dubbo:reference id="userPointsFacade" interface="com.dmall.points.api.UserPointsFacade" timeout="10000" check="false" />

</beans>

5. 测试类

public class UserPonitsTest {

    public static void main(String[] args) throws InterruptedException{
        start();
    }
    public void testApp() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"spring/dubbo-consumer.xml"});
        context.start();

        try {
            System.in.read();               //  为保证服务一直开着,利用输入流的阻塞来模拟
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

6. 使用dubbo-admin包可以对dubbo的服务进行管理和监控。

相关推荐