dubbo面向服务使用

首先启动zookeeper

dubbo集群,使用两个dubbo,一个服务,一个调用,使用zookeeper管理

zeekeeper的功能:管理集群,保证集群成员的数据一致性和动作的协调

服务端:

  server.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="server_first"></dubbo:application>
    <!--协议,所使用服务的名称name="dubbo";提供服务的端口号port="20880"默认-->
    <!--dubbo提供服务的端口-->
    <dubbo:protocol name="dubbo" port="20880"></dubbo:protocol>
    <!--指定注册中心:把服务注册到zookeeper中,要找到这个服务要到zookeeper中-->
    <!--<dubbo:registry address="zookeeper://localhost:2181"/>或者如下,两种方式一样-->
    <dubbo:registry address="zookeeper://localhost" port="2181"></dubbo:registry>

    <!--向外界提供的什么服务,如下-->
    <bean class="service.FirstServiceImp" id="first"></bean>
    <!--向外提供的服务-->
    <dubbo:service interface="service.FirstService" ref="first"></dubbo:service>
    <!--外界使用通过zookeeper找到ref="first"就可使用-->
</beans>

建立接口,要处理的内容

package service;

/**
 * Created by MY on 2017/8/3.
 */
public interface FirstService {
    int sum(int x,int y);
}

创建实现类,实现接口

package service;

/**
 * Created by MY on 2017/8/3.
 */
public class FirstServiceImp implements  FirstService{
    @Override
    public int sum(int x,int y){
        System.out.println("sum()调用了");
        return x+y;
    }
}

创建启动server.xml文件的类

package test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

/**
 * Created by MY on 2017/8/3.
 */
public class DubboServer {
    public static void main(String[] args) {
        //查找配置文件,读取配置文件启动
        ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("server.xml");

        try {
            //不退出当前的进程
            //输入后才退出
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

最后把服务端打包成jar包,在控制台将service下的FirstService.class打包成jar包

F:IDEA docdubbo2outproductiondubbo2>jar cvf a.jar service/FirstService.class

客户端

  除了添加响应的jar包,服务端打包的jar包也要添加进去

  client.cml配置

  创建DubboClient类,启动client.xml文件,调用服务端接口中的方法

package test;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.FirstService;

/**
 * Created by MY on 2017/8/3.
 */
public class DubboClien {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("client.xml");

        FirstService fs = (FirstService) ctx.getBean("fc");
        int s=fs.sum(3,4);
        System.out.println("--"+s);
    }
}
原文地址:https://www.cnblogs.com/rzqz/p/7280172.html