20分钟springboot搭建dubbo服务

本文介绍本人通过springboot搭建dubbo服务的项目实例,此服务为dubbo+springboot+mybatis项目,使用到swagger-ui及mybatis-generator功能。
数据层实现,逆向工程使用部分描述简写,详情参考https://www.jianshu.com/p/6bcaf86e84f0

主体结构如图:


image.png

此服务为父子级maven项目,主体demoDubbo,内嵌:
common(使用mybatis-generator生成实体及mapper,放置实体类);
provider(提供者,放置mapper,提供调用数据层的方法及service接口实现);
api(放置provider的接口,起到关联provider和consumer的作用);
consumer(消费者,存放controller)

0.前期准备:

  1. 本地安装zookeeper(本人使用虚拟机安装的zookeeper,具体自行百度或参考下方链接):
    window安装:https://www.jianshu.com/p/0dbbb97d7e21
    linux安装:https://www.jianshu.com/p/cd6c2110aa71

  2. 数据库执行下面语句,创建d_user表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for d_user
-- ----------------------------
DROP TABLE IF EXISTS `d_user`;
CREATE TABLE `d_user`  (
  `id` int(0) NOT NULL,
  `name` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `ip` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of d_user
-- ----------------------------
INSERT INTO `d_user` VALUES (1001, '雨欣', '100011');
INSERT INTO `d_user` VALUES (1002, '雨欣:324:324:324', '100012');

SET FOREIGN_KEY_CHECKS = 1;

如下:


image.png
  1. 创建maven父级项目
    依次点击idea: File>new>Project新建项目,选择maven,next后创建项目名dubbo新窗口打开,如下:


    image.png

    父级项目删除src,test文件夹。

1.创建common子项目

右键父项目名,new>module如下


image.png

选择maven项目,勾选如下确定,下一步(可不用勾选webapp)


image.png

创建项目名common,依次下一步创建common子项目,删除pom中的<pluginManagement>内容,粘贴逆向工程配置内容,并引入依赖如下:

  <dependencies>

    <dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0</version>
      <scope>compile</scope>
    </dependency>


  </dependencies>

  <build>
    <finalName>common</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
          <configurationFile>
            src/main/resources/generator/genteratorCongfig.xml
          </configurationFile>
          <overwrite>true</overwrite>
          <verbose>true</verbose>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
          </dependency>
          <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.2</version>
          </dependency>
        </dependencies>
      </plugin>
    </plugins>

  </build>

删除main文件夹内的webapps文件夹,创建java,resources文件夹如下:


image.png

!!若文件夹属性不对(后续子项目都会涉及),可点击File>project Structure修改文件属性,如下


image.png

在resources下创建文件夹generator,并创建逆向工程文件配置如下:


image.png

其中config.properties文件内容如下,注意修改你的数据库配置,自动生成的mapper,dao子文件夹名称,以及生成路径

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true
jdbc.user=root
jdbc.password=root


#模块名
moduleName=d_user
#表名
tableName=d_user
#默认路径
modelPath=com.example.demo1

其中genteratorCongfig.xml 文件内容如下

<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="generator/config.properties"/>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
            <property name="caseSensitive" value="true"/>
            <property name="lombok" value="Getter,Setter,ToString"/>
        </plugin>

        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.user}"
                        password="${jdbc.password}">
        </jdbcConnection>

        <!--实体-->
        <javaModelGenerator targetPackage="${modelPath}.model.entity.${moduleName}"
                            targetProject="src/main/java"/>

        <!--mapper.xml-->
        <sqlMapGenerator targetPackage="mapper.${moduleName}"
                         targetProject="./src/main/resources"/>

        <!--mapper接口-->
        <javaClientGenerator targetPackage="${modelPath}.dao.${moduleName}"
                             targetProject="src/main/java"
                             type="XMLMAPPER"/>

        <!--为哪张表生成代码-->
        <table tableName="${tableName}">
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
    </context>
</generatorConfiguration>

双击生成mapper;dao;model如下


image.png

implements Serializable 添加序列化实体对象如下:


image.png

Dubbo服务间的调用需要实体序列化,不然调用会报错:

org.apache.dubbo.remoting.RemotingException: Failed to send response: Response [id=2, version=2.0.2, status=20, event=false, error=null, result=AppResponse [value=com.example.common.model.entity.d_user.DUser@3f3ffb93, exception=null]], cause: java.lang.IllegalStateException: Serialized class com.example.common.model.entity.d_user.DUser must implement java.io.Serializable
java.lang.IllegalStateException: Serialized class com.example.common.model.entity.d_user.DUser must implement java.io.Serializable

生成如下:


image.png

2.创建provider子项目

首先同创建common子项目,创建provider子项目
修改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>org.example</groupId>
  <artifactId>provider</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>provider Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>



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


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <dubbo.version>2.7.8</dubbo.version>
    <!-- dubbo依赖服务版本-->
    <selenium.version>2.53.0</selenium.version>
  </properties>

  <dependencies>
    <!--引入其他子模块-->
    <dependency>
      <groupId>org.example</groupId>
      <artifactId>common</artifactId>
      <version>1.0-SNAPSHOT</version>
      <scope>compile</scope>
    </dependency>

    <!--springboot的Web启动项-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--mysql依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.16</version>
      <scope>runtime</scope>
    </dependency>

    <!--springboot中mybatis依赖自动配置-->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.1.1</version>
    </dependency>

    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
      <scope>compile</scope>
    </dependency>

    <!--测试引入包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

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

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

    <!--tk mybatis 应用的包-->
    <dependency>
      <groupId>tk.mybatis</groupId>
      <artifactId>mapper</artifactId>
      <version>4.1.5</version>
    </dependency>


    <!-- Dubbo 引用 -->
    <!-- Dubbo配置文件引入 -->
    <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-spring-boot-starter</artifactId>
      <version>${dubbo.version}</version>
    </dependency>

    <!-- Zookeeper dependencies -->
    <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-dependencies-zookeeper</artifactId>
      <version>${dubbo.version}</version>
      <type>pom</type>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- dubbo必须依赖服务 -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-server-standalone</artifactId>
      <version>${selenium.version}</version>
    </dependency>


  </dependencies>

  <build>
    <finalName>provider</finalName>
    <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.yml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.yml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    </pluginManagement>
  </build>

</project>

添加并修改yml文件如下:(注意zookeeper配置)

spring:
  application:
    name: this-provider
#  profiles:
#    active: test
  datasource:
    #MySQL数据库支持配置
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true
    username: root
    password: root
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      minimum-idle: 5
      maximum-pool-size: 100
      idle-timeout: 600000
      pool-name: OrderHikariCP
      max-lifetime: 1800000
      connection-timeout: 60000
      connection-test-query: SELECT 1
server:
  port: 8081
mybatis:
  config-location: classpath:mybatis-config.xml
  type-aliases-package: org.example.provider.dao.**
  mapper-locations: classpath:mapper/*/*.xml
dataType: 0

dubbo:
  # Base packages to scan Dubbo Component: @org.apache.dubbo.config.annotation.Service
  scan:
    # 扫描 DubboService 注解
    base-packages: org.example.provider.**
  ## ApplicationConfig Bean
  application:
    # 服务id
    id: this-provider
    # 服务名称
    name: this-provider
    # QOS服务:通过一些命令来返回响应的结果,达到动态控制的目的
    qos-port: 22212
    qos-enable: true
  ## ProtocolConfig Bea                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        n
  protocol:
    # 底层通讯协议,在多协议时使用?
    id: dubbo
    name: dubbo
    port: 10345
    status: server
    payload: 83886080
  ## RegistryConfig Bean
  registry:
    id: this-provider
    # 使用的zookeeper 地址
    address: 10.1.31.199:2181
    protocol: zookeeper
  provider:
    # 当 ProtocolConfig 和 ServiceConfig 某属性没有配置时,采用此缺省值,可选
    timeout: 300000
    payload: 83886080
  consumer:
    # 当 ReferenceConfig 某属性没有配置时,采用此缺省值,可选
    timeout: 300000
    check: false

添加并修改mybatis-config文件如下:

<?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>
    <properties resource="application.yml">
        <property name="dataType" value="${dataType}"/>
    </properties>
    <settings>
        <!-- 在null时也调用 setter,适应于返回Map,3.2版本以上可用 -->
        <setting name="callSettersOnNulls" value="true"/>
        <!-- 全局映射器启用缓存 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- 查询时,关闭关联对象即时加载以提高性能 -->
        <setting name="lazyLoadingEnabled" value="false"/>
        <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!-- 允许使用列标签代替列名 -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
        <!--<setting name="autoMappingBehavior" value="FULL" />-->
        <!-- 对于批量更新操作缓存SQL以提高性能  -->
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <!-- 数据库超过25000秒仍未响应则超时 -->
        <setting name="defaultStatementTimeout" value="25000"/>
    </settings>

</configuration>

再将common的dao层及mapper文件夹移至provider中(pom内引入common依赖后,修改引入路径),
整体结构如下:


image.png

在mapper.xml文件内编写sql查询语句,并在dao内,添加该方法:

  <sql id="User_Num">
    id,name,ip
  </sql>
  <!--查询-->
  <select parameterType="Integer" id="selectAllById" resultType="com.example.common.model.entity.d_user.DUser">
    SELECT
    <include refid="User_Num"/>
    FROM d_user WHERE id = #{id}
  </select>
    DUser selectAllById(@Param("id") Integer id);

创建service文件夹,预留存放Service接口实现;
创建application启动类文件ProviderApplication如下:

package com.example.provider;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import tk.mybatis.spring.annotation.MapperScan;

/**
 * 订单provider启动类
 *
 * @author ZSC-DXHY
 */

@SpringBootApplication
@ComponentScan(value = {"com.example"})
@MapperScan(basePackages = "com.example.provider.dao.**")
@EnableConfigurationProperties
@EnableDubbo
public class ProviderApplication extends SpringBootServletInitializer {
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ProviderApplication.class);
    }
    
    public static void main(String[] args) {
        new SpringApplicationBuilder(ProviderApplication.class)
                .run(args);
    }
}

创建test测试项,测试数据查询实现如下:
在src下创建文件夹test,修改文件夹属性为Tests,在目录下创建providerApplicationTests测试类代码如下:

package com.example.demomybatis;
import com.example.provider.ProviderApplication;
import com.example.provider.dao.d_user.DUserMapper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.junit.runner.RunWith;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProviderApplication.class)
public class providerApplicationTests {

    @Autowired
    DUserMapper dUserMapper;


    @Test
    public void contextLoads() {
        System.out.println("here==="+dUserMapper.selectAllById(1001).getName());
    }


}

启动测试文件,查询成功:


image.png

整体结构如下:


image.png

3.创建api子项目

首先同创建common子项目,创建api子项目,并创建文件夹java/com/example/api,添加service接口层,如下:


image.png

在api的service内添加接口方法DUserService;
在provider的service创建impl文件夹,并在内添加接口方法的实现类DUserServiceImpl实现DUserService接口。
代码如下:

package com.example.api.service;

import com.example.common.model.entity.d_user.DUser;

public interface DUserService {
    DUser selectById(Integer id);
}

package com.example.provider.service.impl;


import com.example.api.service.DUserService;
import com.example.common.model.entity.d_user.DUser;
import com.example.provider.dao.d_user.DUserMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

@DubboService
public class DUserServiceImpl implements DUserService {

    @Autowired
    DUserMapper dUserMapper;

    @Override
    public DUser selectById(Integer id){
        return dUserMapper.selectAllById(id);
    }
}

注意:
1dubbo的service注解使用DubboService
2为api项目的pom添加common依赖,为provider项目添加api依赖

3.创建consumer子项目

首先同创建common子项目,创建consumer子项目,并创建目录结构;
consumer使用swagger-ui接口,大致创建可仿common及provider子项目实现,具体结构如下:


image.png

其中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>org.example</groupId>
  <artifactId>consumer</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>consumer Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>



  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <dubbo.version>2.7.8</dubbo.version>
    <!-- dubbo依赖服务版本-->
    <selenium.version>2.53.0</selenium.version>
  </properties>

  <dependencies>
    <!--springboot的Web启动项-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Dubbo 引用 -->
    <!-- Dubbo配置文件引入 -->
    <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-spring-boot-starter</artifactId>
      <version>${dubbo.version}</version>
    </dependency>

    <!-- Zookeeper dependencies -->
    <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-dependencies-zookeeper</artifactId>
      <version>${dubbo.version}</version>
      <type>pom</type>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- dubbo必须依赖服务 -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-server-standalone</artifactId>
      <version>${selenium.version}</version>
    </dependency>

    <!--引入的其他子模块-->

    <!--swagger依赖-->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>com.spring4all</groupId>
      <artifactId>spring-boot-starter-swagger</artifactId>
      <version>1.5.1.RELEASE</version>
    </dependency>
    <!-- 阿里fastjson包JSON转换-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>
    
    <dependency>
      <groupId>org.example</groupId>
      <artifactId>api</artifactId>
      <version>1.0-SNAPSHOT</version>
      <scope>compile</scope>
    </dependency>

  </dependencies>

  <build>
    <finalName>consumer</finalName>
  </build>
</project>

application.yml文件如下:

spring:
  application:
    name: consumer
  profiles:
    active: test
server:
  port: 8082
  servlet:
    context-path: /
  max-http-header-size: 4048576


dubbo:
  # Base packages to scan Dubbo Component: @org.apache.dubbo.config.annotation.Service
  scan:
    # 扫描 DubboService 注解
    base-packages: org.example.consmuer.**
  ## ApplicationConfig Bean
  application:
    # 服务id
    id: this-consumer
    # 服务名称
    name: this-consumer
    # QOS服务:通过一些命令来返回响应的结果,达到动态控制的目的
    qos-port: 22213
    qos-enable: true
  ## RegistryConfig Bean
  registry:
    id: this-provider
    # 使用的zookeeper 地址
    address: 10.1.31.199:2181
    protocol: zookeeper
  provider:
    # 当 ProtocolConfig 和 ServiceConfig 某属性没有配置时,采用此缺省值,可选
    timeout: 300000
  consumer:
    # 当 ReferenceConfig 某属性没有配置时,采用此缺省值,可选
    timeout: 300000
    check: false

swagger2Config文件如下:

package com.example.config;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())// 对所有api进行监控
                .paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控
                .paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测试swagger-dubbo接口")
                .description("dxhy-api文档")
                // .termsOfServiceUrl("/")
                .version("1.0")
                .build();
    }
}

创建的controller实现类文件如下:

package com.example.consumer.openapi;


import com.example.api.service.DUserService;
import com.example.common.model.entity.d_user.DUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

@Api(value = "demo",description = "API for demo",protocols = "http")
@RestController
@RequestMapping("/demo")
public class testController {

    @DubboReference
    private DUserService duserService;

    @ApiOperation(value="",notes="")
    @GetMapping("/getById")
    public DUser demoForController(@RequestParam(value="id",defaultValue ="1001" )@ApiParam(value="uersId")String id){
        DUser user =new DUser();
        if(StringUtils.isNotEmpty(id)){
            user = duserService.selectById(Integer.valueOf(id));
        }
        return user;
    }
}

注意:duserService接口引入api的,注解使用:@DubboReference
启动项文件ConsumerStarter 内容为:

package com.example.consumer;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 订单服务启动类
 *
 * @author ZSC-DXHY
 */
@SpringBootApplication
@ComponentScan(value = {"com.example"})
@EnableDubbo
@EnableSwagger2
public class ConsumerStarter extends SpringBootServletInitializer {
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ConsumerStarter.class);
    }
    
    public static void main(String[] args) {
        new SpringApplicationBuilder(ConsumerStarter.class)
                .run(args);
    }
    
}

至此项目创建完毕。

5测试项目功能实现

先启动provider服务;


image.png

再启动consumer服务;


image.png

浏览器访问swagger-ui链接如下:

http://localhost:8082/swagger-ui.html#!/test-controller/demoForControllerUsingGET
image.png

整体实现成功~

注意:此文章写的比较粗糙,但是整体实现没问题,父子级关系并未实现依赖引用包,后续完善~
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,098评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,213评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,960评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,519评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,512评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,533评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,914评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,574评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,804评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,563评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,644评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,350评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,933评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,908评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,146评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,847评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,361评论 2 342

推荐阅读更多精彩内容