springboot整合dubbo入门介绍

1.dubbo介绍

   dubbo-user-book : http://dubbo.apache.org/books/dubbo-user-book

   duboo的服务注册中心有如下几种:

1.1 Multicast 注册中心
1.2 Redis 注册中心
1.3 Simple 注册中心
1.4  zookeeper 注册中心(常用,dubbo推荐使用此服务注册中心) 

Zookeeper 是 Apacahe Hadoop 的子项目,是一个树型的目录服务,支持变更推送,适合作为 Dubbo 服务的注册中心,工业强度较高,可用于生产环境。

/user-guide/images/zookeeper.jpg

流程说明:

  • 服务提供者启动时: 向 /dubbo/com.foo.BarService/providers 目录下写入自己的 URL 地址
  • 服务消费者启动时: 订阅 /dubbo/com.foo.BarService/providers 目录下的提供者 URL 地址。并向 /dubbo/com.foo.BarService/consumers 目录下写入自己的 URL 地址
  • 监控中心启动时: 订阅 /dubbo/com.foo.BarService 目录下的所有提供者和消费者 URL 地址。

支持以下功能:

  • 当提供者出现断电等异常停机时,注册中心能自动删除提供者信息
  • 当注册中心重启时,能自动恢复注册数据,以及订阅请求
  • 当会话过期时,能自动恢复注册数据,以及订阅请求
  • 当设置 <dubbo:registry check="false" /> 时,记录失败注册和订阅请求,后台定时重试
  • 可通过 <dubbo:registry username="admin" password="1234" /> 设置 zookeeper 登录信息
  • 可通过 <dubbo:registry group="dubbo" /> 设置 zookeeper 的根节点,不设置将使用无根树
  • 支持 * 号通配符 <dubbo:reference group="*" version="*" />,可订阅服务的所有分组和所有版本的提供者
    本文的的列子是基于zookeeper服务注册中心开展

2.zookeeper安装zookeeper安装

安装单机版即可 

2.1 下载zookeepre-x.x.x.tar.gz并设置为环境变量

      下载url : http://apache.fayea.com/zookeeper

2.2 解压tar.gz文件

      tar -zxvf zookeepre-3.4.9.tar.gz

     注意:zookeeper要求Java运行环境,并且需要jdk版本1.6以上。为了以后的操作方便,可以对zookeeper的环境变量进行配置(该步骤可忽略)。方法如下,在/etc/profile文件中加入以下内容:


#Set Zookeeper Environment

设置完后,你需要使用source /etc/profile 环境变量即可生效

2.3 修改zookeeper的配置文件

进入conf文件夹,复制zoo_sample.cfg文件并修改名称为zoo.cfg

简单实用可只修改如下的几个配置即可:


tickTime : 服务器与客户端之间交互的基本时间单元(ms)
dataDir : 保存zookeeper数据路径
dataLogDir : 保存zookeeper日志路径,当此配置不存在时默认路径与dataDir一致
clientPort : 客户端访问zookeeper时经过服务器端时的端口号

zookeepserver.id=host:port:port : 表示了不同的zookeeper服务器的自身标识,作为集群的一部分,每一台服务器应该知道其他服务器的信息。用户可以从“server.id=host:port:port” 中读取到相关信息。


在服务器的data(dataDir参数所指定的目录)下创建一个文件名为myid的文件,这个文件的内容只有一行,指定的是自身的id值。比如,服务器“1”应该在myid文件中写入“1”。这个id必须在集群环境中服务器标识中是唯一的,且大小在1~255之间。这一样配置中,zoo1代表第一台服务器的IP地址。第一个端口号(port)是从follower连接到leader机器的端口,第二个端口是用来进行leader选举时所用的端口。

修改后我们可以使用zkServer.sh start/restart来启动服务:


出现上图中红框标识的文字zookeeper及启动成功
如果你未配置环境变量那么你需要进入zookeeper/bin文件夹 运行 ./zkServersh start 来启动zk
启动完成侯检验是否zk已正常启动,使用命令jps, 进程QuorumPeerMain为zookeeper的进程即启动成功

然后你可以使用zkCli.sh来来接zookeeper,如图2181即为你上面配置的clientPort对应


3.编写dubbo的demo

3.1 建立一个空的mvn工程作为父工程

由于cusmer模块需要使用到provider服务提供方模块的类,我们可以使用一个父工程将子模块整合然后各个模块之间可以相互依赖
   


然后添加子模块



完成后的目录结构如下


3.1 服务提供方示例

3.1.1 首先我们需要添加dubbo的依赖,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lsm.provider</groupId>
    <artifactId>provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>provider</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

        <!-- 设置我们项目的一些版本属性 -->

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
        <dubbo.version>2.5.5</dubbo.version>
        <zkclient.version>0.10</zkclient.version>
        <lombok.version>1.16.18</lombok.version>
        <spring-boot.version>1.5.7.RELEASE</spring-boot.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Dubbo依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!--dubbo远程调用依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo-rpc-dubbo</artifactId>
        </dependency>

        <!---->
        <dependency>
            <groupId>com.netflix.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>1.3.3</version>
        </dependency>

        <!--zookeeper需要的依赖-->
        <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.12.0</version>
        </dependency>

        <!-- Spring Boot log4j依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

需注意:dubbo的版本需要和后面关于dubbo的xm配置文件中的dubbo.xsd保持版本一致


否则可能此文件中的<dubbo:application>等标签无法使用,而报错;(之前我以为是网络原因无法加载xsd文件,但是发现我将xsd文件下载下来一样无法使用,而改对了版本后就可正常使用);

3.1.2 编写服务接口,以及实现类

服务接口:

package com.lsm.provider.provider.service;

import com.lsm.provider.provider.domain.Product;

import java.util.List;

public interface ProductService {
    void sayHello(String name);
    Product insert(Product product);

    List<Product> findAll(Product product);
}

服务接口实现类:

package com.lsm.provider.provider.service.impl;

import com.lsm.provider.provider.domain.Product;
import com.lsm.provider.provider.mapper.ProductMapper;
import com.lsm.provider.provider.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductMapper productMapper;

    @Override
    public void sayHello(String name) {
        System.out.println("hello, " + name);
    }

    @Override
    public Product insert(Product product) {
        productMapper.insert(product);
        return product;
    }

    @Override
    public List<Product> findAll(Product product) {
        return productMapper.findAll(product);
    }
}

使用xml方式将服务暴露到服务注册中心:

编写dubbo-demo-provider.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <!-- provider's application name, used for tracing dependency relationship -->
    <dubbo:application name="demo-provider"/>

    <!-- use multicast registry center to export service -->
    <!--<dubbo:registry address="multicast://224.5.6.7:1234"/>-->

    <dubbo:registry address="zookeeper://127.0.0.1:2181" />


    <!-- use dubbo protocol to export service on port 20880 -->
    <dubbo:protocol name="dubbo" port="20880"/>

    <!-- service implementation, as same as regular local bean -->
    <bean id="productService" class="com.lsm.provider.provider.service.impl.ProductServiceImpl"/>

    <!-- declare the service interface to be exported -->
    <dubbo:service interface="com.lsm.provider.provider.service.ProductService" ref="productService"/>

    <!-- service implementation, as same as regular local bean -->
    <bean id="demo1Service" class="com.lsm.provider.provider.service.impl.DemoServiceImpl"/>

    <!-- declare the service interface to be exported -->
    <dubbo:service interface="com.lsm.provider.provider.service.DemoService" ref="demo1Service"/>

</beans>
dubbo:application:当前应用名称,用于注册中心计算应用间依赖关系,注意:消费者和提供者应用名不要一样
dubbo:registry: 制定服务注册中心,服务注册中新的协议有很多中,因此我们需要通过协议头来指定你使用的是什么服务注册中心
zookeeper://xxxxx 中的zookeeper:即为协议头
dubbo:protocol:协议配置,用于配置提供服务的协议信息,协议由提供方指定,消费方被动接受
dubbo:service:引用服务配置,用于创建一个远程服务代理,并在服务中心暴露出来供消费者调用

上面的xml的配置如何生效,我们需要在启动类加入如下的配置:

package com.lsm.provider.provider;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:dubbo-demo-provider.xml")
// MyBatis 支持
@MapperScan("com.lsm.provider.provider.mapper")
public class ProviderApplication {

	public static void main(String[] args) {
		SpringApplication.run(ProviderApplication.class, args);
	}
}

使用@ImportResource来进行xml配置的装载

然后启动项目:


通过启动的日志可以看的出来,dubbo将我们写的服务接口暴露到配置的服务注册中心,这个时候我们可以通过zkCli客户端来查看zookeeper的节点信息:


是用命令 ls / 查看根节点信息,可以看到我们启动服务后,他自动在根节点下添加一个dubbo的节点,然后我们继续查看dubbo的节点信息


可以看到下面的节点分别是我们在配置文件中暴露的服务接口,接下来我们再看看每一个服务接口节点的信息


可以看到节点下面多处了四个节点:

consumer: 消费者,表示有哪些消费者‘订阅’了这个服务。

providers:提供者,表示服务提供方提供的所有服务

由于我们已经暴露的服务,可以查看一下providers节点的信息:


保存的是该服务下具体暴露的服务信息,在信息中可以看到我们定义的方法findAll等;

consumer:节点下目前无信息


总结:

     我们可以看到,每个服务(URL)在dubbo节点下都会有一个对应的ZK持久化节点,而每个服务节点下面都会有四个持久化子节点,代表消费者(consumer)、路由(routers)、提供者(providers)和配置(configurators),consumer和providers节点好理解,放的就是该URL下消费者和提供者的URL全部信息,而routers和configurators主要用于控制路由规则,这在正常情况下是用的比较少的,所以这两个节点数据通常为空。

如此,我们就实现了如何将我们的服务暴露到服务注册中心,现在就可以被消费者调用了

3.2 服务消费者

和服务提供方一样我们需要在pom文件中添加对应的依赖;这里不再重复展示;

3.2.1 编写服务消费者的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <!-- consumer's application name, used for tracing dependency relationship (not a matching criterion),
    don't set it same as provider -->
    <dubbo:application name="demo-consumer"/>

    <!-- use multicast registry center to discover service -->
    <!--<dubbo:registry address="multicast://224.5.6.7:1234"/>-->

    <dubbo:registry address="zookeeper://127.0.0.1:2181" />
    <!-- generate proxy for the remote service, then demoService can be used in the same way as the
    local regular interface -->
    <dubbo:reference id="productService"  check="false" interface="com.lsm.provider.provider.service.ProductService"/>


</beans>

文件中其他的标签和服务提供者一致,多了一个dubbo:reference

节点表示引用一个服务,其中 id 表示该服务的唯一标识,可以用该 id 实现 IOC 注入,interface 表示引用的服务接口;

同样的我们也需要将配置文件通过@importResource注解来装配

服务引用的示例:

package com.lsm.customer.service.impl;

import com.lsm.customer.service.ProductCliService;
import com.lsm.provider.provider.domain.Product;
import com.lsm.provider.provider.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductCliServiceImpl implements ProductCliService {
    @Autowired
    private ProductService productService;

    @Override
    public List<Product> showProducts() {
        Product product = new Product();
        product.setName("lsm");
        List<Product> products = productService.findAll(product);
        return products;
    }

    @Override
    public Product createProduct(Product product) {
        Product productDb = productService.insert(product);
        return productDb;
    }
}

在消费者代码中调用时我们可以直接通过@Autowored标签直接注入进来即可

到此服务消费者已经编写完毕,启动后我们再次通过zkCli.sh命令查看对应的节点信息
cusmers节点下面会出现如下信息:


通过日记可查看到消费者订阅了我们发布的服务


到这里我们基本上一个完整的demo就算完成了,本文只是记录下整个demo的搭建过程和步骤,有待继续深入研究;

猜你喜欢

转载自blog.csdn.net/mingping1/article/details/80792862