Dubbo之快速搭建dubbo应用框架demo

Posted zengnansheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Dubbo之快速搭建dubbo应用框架demo相关的知识,希望对你有一定的参考价值。

一、安装zookeeper

此处省略

 

二、安装dubbo-admin

 

可以去https://github.com/alibaba/dubbo/releases下载源码用Eclipse将dubbo-admin项目打成War包或网络下载War包

将dubbo-admin.war包放到Tomcat的Webapps目录下,并启动Tomcat,然后访问http://localhost/dubbo-admin/

登录用户密码可以从WEB-INF下的dubbo.properties文件中看到,

root账号默认密码为root,guest账号默认密码为guest

登录后即可用看到管理界面

 

三、搭建服务接口工程

product_service_interface 服务接口(用于提供者和消费者共享)  jar工程

 

项目工程结构如下

product_service_interface

  src

     main

        java

           com.zns.product

              dto

                  ProductDto

              service

  ProductService

  pom.xml

 

ProductDto

package com.zns.product.dto;

import java.io.Serializable;

public class ProductDto implements Serializable {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

 

ProductService

package com.zns.product.service;

import com.zns.product.dto.ProductDto;

public interface ProductService {
     ProductDto queryById(Integer id);
}

 

 

四、搭建服务提供者工程

product_service_provider 服务提供者  jar工程

项目工程结构如下

product_service_provider

  src

     main

        java

           com.zns.product

              mapper

                  ProductMapper

      model

                  Product

              service

  ProductServiceImpl

      ProviderAPP.java

         resources

              jdbc.properties

              dubbo-provider.properties

              dubbo-provider.xml

      mybatis

  sqlmapper

      ProductMapper.xml

          mybatis-config.xml

      spring

                  spring-context.xml

  spring-mybatis.xml

  pom.xml


pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>4.3.5.RELEASE</spring.version>
</properties>

<dependencies>
    <!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>
    <!-- mybatis 包 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.8</version>
    </dependency>
    <!--mybatis和spring整合包 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.2</version>
    </dependency>
    <!-- mysql连接驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.34</version>
    </dependency>
    <!-- druid 连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.10</version>
    </dependency>
    <!-- dubbo -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dubbo</artifactId>
        <version>2.5.6</version>
        <exclusions>
            <exclusion>
                <artifactId>spring</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <!-- zookeeper -->
    <dependency>
        <groupId>com.101tec</groupId>
        <artifactId>zkclient</artifactId>
        <version>0.4</version>
    </dependency>
    <!-- product_service_interface -->
    <dependency>
        <groupId>com.zns</groupId>
        <artifactId>product_service_interface</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

 


Product

package com.zns.product.model;

import java.io.Serializable;

public class Product implements Serializable {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

 

ProductMapper

package com.zns.product.mapper;

import com.zns.product.model.Product;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductMapper {
    Product queryById(Integer id);
}

 

 

ProductServiceImpl

package com.zns.product.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.zns.product.dto.ProductDto;
import com.zns.product.mapper.ProductMapper;
import com.zns.product.model.Product;
import org.springframework.beans.factory.annotation.Autowired;

@Service(interfaceClass = ProductService.class)
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public ProductDto queryById(Integer id) {
        Product product = productMapper.queryById(id);
        ProductDto productDto = new ProductDto();
        productDto.setId(product.getId());
        productDto.setName(product.getName());
        return productDto;
    }
}

 

ProductMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zns.product.mapper.ProductMapper">
    <select id="queryById" parameterType="int" resultType="com.zns.product.model.Product">
        select id,name from t_product where id=#{productId}
    </select>
</mapper>

 

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!-- 返回resultType为map时,如果数据为空的字段,则该字段会省略不显示, 可以通过添加该配置,返回null -->
    <settings>
        <setting name="callSettersOnNulls" value="true" />
    </settings>
</configuration>

 

spring-context.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan  annotation-config="true" base-package="com.zns.product.service" />

    <!--引入xml-->
    <import resource="classpath:spring/spring-mybatis.xml"/>
    <import resource="classpath:dubbo-provider.xml"/>

</beans>

 

 

spring-mybatis.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 引入外部属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" ignore-resource-not-found="true" />

    <!-- 配置druid连接池: -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="filters" value="stat" />
        <!--连接池的最大数据库连接数。设为0表示无限制。一般把maxActive设置成可能的并发量就行了-->
        <property name="maxActive" value="1000" />
        <!--初始化大小-->
        <property name="initialSize" value="10" />
        <!--最大等待毫秒数, 单位为 ms, 如果超过此时间将接到异常,设为-1表示无限制-->
        <property name="maxWait" value="60000" />
        <!--最大等待(空闲)连接中的数量,设 0 为没有限制-->
        <property name="maxIdle" value="100" />
        <!--最小等待(空闲)连接中的数量-->
        <property name="minIdle" value="10" />
        <!--在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位. 如果设置为非正数,则不运行空闲连接回收器线程-->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!--连接池中保持空闲而不被空闲连接回收器线程 ,回收的最小时间值,单位毫秒-->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <!--SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前.如果指定, 则查询必须是一个SQL SELECT并且必须返回至少一行记录-->
        <property name="validationQuery" value="SELECT ‘x‘" />
        <!--指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败, 则连接将被从池中去除.
        注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串-->
        <property name="testWhileIdle" value="true" />
        <!--指明是否在从池中取出连接前进行检验,如果检验失败 则从池中去除连接并尝试取出另一个. 注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串-->
        <property name="testOnBorrow" value="false" />
        <!--指明是否在归还到池中前进行检验-->
        <property name="testOnReturn" value="false" />
        <!--开启池的prepared statement 池功能  mysql不支持-->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="50" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <!-- mapper xml路径 -->
        <property name="mapperLocations" value="classpath:mybatis/sqlmapper/*.xml" />
    </bean>

    <!-- 配置mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描这个包以及它的子包下的所有映射接口类,多个包逗号隔开 -->
        <property name="basePackage" value="com.zns.product.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 配置Spring的事务管理器 与mabatis整合是用jdbc事务 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

 

 

jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password =123456

 

 

dubbo-provider.properties

dubbo.registry.name=product_service_provider
dubbo.registry.cache=/data/dubbo/cache/${dubbo.registry.name}.cache
dubbo.registry.address=127.0.0.1:2181
dubbo.protocol.host=192.168.1.101
dubbo.transport.port=20880
dubbo.transport.version=1.0.0

 

 

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:context="http://www.springframework.org/schema/context"
   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://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
         http://code.alibabatech.com/schema/dubbo
           http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

   <context:property-placeholder location="classpath:dubbo-provider.properties" ignore-unresolvable="true" ignore-resource-not-found="true" />
   <dubbo:application name="${dubbo.registry.name}" />
   <dubbo:protocol name="dubbo" host="${dubbo.protocol.host}" port="${dubbo.transport.port}"  accesslog="true" charset="UTF-8"  />
   <dubbo:provider version="${dubbo.transport.version}" loadbalance="leastactive" delay="-1" timeout="10000" cluster="failfast" retries="0" />
   <dubbo:registry address="${dubbo.registry.address}" file="${dubbo.registry.cache}" protocol="zookeeper" version="${dubbo.transport.version}" />
   <dubbo:annotation package="com.zns.product.service" />

</beans>

 

 

ProviderAPP 启动dubbo服务文件  开发期间调试可以这样用,实际生产不建议

package com.zns.product;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ProviderAPP {
    public static void main(String[] args) {
        try {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");
            context.start();
            System.out.print("启动成功");
        } catch (Exception e) {
            System.out.print(e.toString());
        }
        synchronized (ProviderAPP.class) {
            while (true) {
                try {
                    ProviderAPP.class.wait();
                } catch (InterruptedException e) {
                    System.out.print(e.toString());
                }
            }
        }
    }
}

 

 

五、搭建服务消费者工程

springboot_consumer  以springboot工程作为客户端

项目工程结构如下

springboot_consumer

  src

     main

        java

           com.zns

              config

                  DubboConfig

      controller

                  ProductController

      ConsumerApp.java

         resources

              application.properties

              dubbo-consumer.properties

              dubbo-consumer.xml

  pom.xml

 

pom.xml

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.0.RELEASE</version>
    </parent>
    <artifactId>springboot_consumer</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </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>2.5.6</version>
            <exclusions>
                <exclusion>
                    <artifactId>spring</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- zookeeper -->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.4</version>
        </dependency>
        <!-- product_service_interface -->
        <dependency>
            <groupId>com.zns</groupId>
            <artifactId>product_service_interface</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

 

 

application.properties

server.name=springboot_consumer
server.port=9000
server.context-path=/

 

 

dubbo-consumer.properties

dubbo.registry.name=springboot_consumer
dubbo.registry.cache=/data/dubbo/cache/${dubbo.registry.name}.cache
dubbo.registry.address=127.0.0.1:2181
dubbo.protocol.host=192.168.1.101
dubbo.transport.port=20880
dubbo.transport.version=1.0.0

 

 

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:context="http://www.springframework.org/schema/context"
   xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
         http://code.alibabatech.com/schema/dubbo
           http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

   <context:property-placeholder location="classpath:dubbo-consumer.properties" ignore-unresolvable="true" />

   <dubbo:application name="${dubbo.registry.name}" />
   <dubbo:protocol name="dubbo" host="${dubbo.protocol.host}" port="${dubbo.transport.port}"  accesslog="true" charset="UTF-8"  />
   <dubbo:consumer version="${dubbo.transport.version}" proxy="javassist" loadbalance="leastactive" check="false" timeout="30000" />
   <dubbo:registry address="${dubbo.registry.address}" file="${dubbo.registry.cache}" protocol="zookeeper" version="${dubbo.transport.version}" />
   <dubbo:annotation package="com.zns" />

</beans>

 

 

DubboConfig

package com.zns.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource({ "classpath:dubbo-consumer.xml" })
public class DubboConfig {

}

 

 

ProductController

package com.zns.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zns.product.dto.ProductDto;
import com.zns.product.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Reference
    private ProductService productService;

    @RequestMapping("/queryById/{id}")
    @ResponseBody
    public ProductDto queryById(@PathVariable("id") Integer id) {
        return productService.queryById(id);
    }
}

 

 

ConsumerApp

package com.zns;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumerApp {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(ConsumerApp.class);
        application.run(args);
    }
}

 

 

启动zookeeper

启动dubbo-admin管理后台

启动服务提供者

启动服务消费者

刷新dubbo-admin管理后台可以看到有提供者和消费者注册信息

然后测试消费者调用提供者服务

 

 




以上是关于Dubbo之快速搭建dubbo应用框架demo的主要内容,如果未能解决你的问题,请参考以下文章

Dubbo入门---搭建一个最简单的Demo框架

Dubbo入门---搭建一个最简单的Demo框架

Dubbo入门---搭建一个最简单的Demo框架

Dubbo入门---搭建一个最简单的Demo框架

Dubbo入门--搭建一个最简单的Demo框架

Dubbo 入门系列之快速部署一个微服务应用