SpringBoot集成Dubbo

有些话、适合烂在心里 提交于 2020-01-25 04:18:11

1.构建环境
1.1安装zookeeper,参考链接 https://blog.csdn.net/qq_33316784/article/details/88563482
1.2下载运行 dubbo-admin 下载地址:https://github.com/apache/dubbo/tree/2.5.x
环境配置完成后,启动zookeeper和dubbo-admin服务

2.构建dubbo服务消费者,服务提供者

项目结构
在这里插入图片描述
创建一个项目springboot-dubbo ,相关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>

    <groupId>top.xzhand.springboot-dubbo</groupId>
    <artifactId>springboot-dubbo</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>provider</module>
        <module>consumer</module>
        <module>provider-sdk</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <spring.boot.version>2.1.2.RELEASE</spring.boot.version>
    </properties>
    <dependencies>
        <!--springboot相关jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.32</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
        </dependency>
       
    </dependencies>

</project>

新建prodvider-sdk
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">
    <parent>
        <artifactId>springboot-dubbo</artifactId>
        <groupId>top.xzhand.springboot-dubbo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>provider-sdk</artifactId>


</project>

新建接口类 UserService

package top.xzhand.service;


import top.xzhand.dto.UserInfoDto;

public interface UserService {


    Integer insertSelective(UserInfoDto record);

    UserInfoDto selectByPrimaryKey(Long id);

    Integer updateByPrimaryKeySelective(UserInfoDto record);

}

package top.xzhand.dto;

import lombok.Data;

import java.io.Serializable;
import java.util.Date;
@Data
public class UserInfoDto implements Serializable {
    private Long id;

    private String username;

    private String password;

    private String mobile;

    private Date createAt;

    private Date updateAt;

    private Integer status;

    private String photoUrl;

    private String nickname;

    private String wxId;

}

新建模块provider服务提供者
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">
    <parent>
        <artifactId>springboot-dubbo</artifactId>
        <groupId>top.xzhand.springboot-dubbo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>provider</artifactId>

    <dependencies>

        <!--dubbo 依赖 -->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- zookeeper client依赖 -->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- Druid数据库连接池组件 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--mybatis自动生成工具-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
            <scope>test</scope>
        </dependency>

        <!-- mybatis 工具包-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <artifactId>provider-sdk</artifactId>
            <groupId>top.xzhand.springboot-dubbo</groupId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.22</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>

    </build>
</project>

数据库配置:

package top.xzhand.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class Druidconfig {

    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }
}

application.yml

server:
  port: 8081

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/june?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: root123
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      #最大活跃数
      maxActive: 20
      #初始化数量
      initialSize: 1
      #最大连接等待超时时间
      maxWait: 60000
      #打开PSCache,并且指定每个连接PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      #通过connectionProperties属性来打开mergeSql功能;慢SQL记录
      #connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 1 from dual
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
      filters: stat, wall, log4j

  dubbo:
    application:
      name: provider
    server: true
    registry:
      address: zookeeper://127.0.0.1:2181
    protocol:
      name: dubbo
      port: 20880
mybatis:
  # 数据库映射实体类包路径
  type-aliases-package: top.xzhand.model
  mapper-locations:  classpath*:top/xzhand/mapper/impl/*.xml
  # 表中的字段名与对象的属性名下划线和驼峰转换
  configuration:
    map-underscore-to-camel-case: true


generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- mvn mybatis-generator:generate     项目路径下执行,注意配置maven环境变量-->
<generatorConfiguration>

    <context id="default" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库连接配置-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/june"
                        userId="root"
                        password="root123">
        </jdbcConnection>

        <!--实体类路径配置-->
        <javaModelGenerator targetPackage="top.xzhand.model"
                            targetProject="./src/main/java">
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--mapper.xml 文件路径配置-->
        <sqlMapGenerator targetPackage="top.xzhand.mapper.impl"
                         targetProject="./src/main/java">
        </sqlMapGenerator>

        <!--mapper文件路径配置-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="top.xzhand.mapper"
                             targetProject="./src/main/java">
        </javaClientGenerator>

        <!--数据库对应表配置-->
        <table tableName="user_info" domainObjectName="UserInfo"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>

    </context>
</generatorConfiguration>

使用generator生成model,mapper,xml。

ProviderApplication.java
一定要添加@EnableDubboConfiguration注解,注册到dubbo服务上

package top.xzhand;

import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Arrays;

@SpringBootApplication
@EnableDubboConfiguration
@MapperScan("top.xzhand.mapper")
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class);
    }

	@Bean
	public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
		return args -> {
			System.out.println("Let's inspect the beans provided by Spring Boot:");
			String[] beanNames = ctx.getBeanDefinitionNames();
			Arrays.sort(beanNames);
			for (String beanName : beanNames) {
				System.out.println(beanName);
			}
		};
	}
}

UserServiceImpl.java

package top.xzhand.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.xzhand.dto.UserInfoDto;
import top.xzhand.mapper.UserInfoMapper;
import top.xzhand.model.UserInfo;
import top.xzhand.service.UserService;

@Service
@Component
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public Integer insertSelective(UserInfoDto record) {
        UserInfo userInfo=new UserInfo();
        try {
            BeanUtils.copyProperties(record, userInfo);
            return userInfoMapper.insertSelective(userInfo);
        }catch (Exception e){
            e.printStackTrace();
            log.error("添加失败:UserInfoDto:"+ JSON.toJSONString(record));
            return null;
        }

    }

    @Override
    public UserInfoDto selectByPrimaryKey(Long id) {
        UserInfoDto userInfoDto=new UserInfoDto();
        try{
            UserInfo userInfo=userInfoMapper.selectByPrimaryKey(id);
            BeanUtils.copyProperties(userInfo,userInfoDto);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询失败:id:"+ id);
            return userInfoDto;
        }

        return userInfoDto;
    }

    @Override
    public Integer updateByPrimaryKeySelective(UserInfoDto record) {
        UserInfo userInfo=new UserInfo();
        try{
            BeanUtils.copyProperties(record,userInfo);
            return userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改失败:UserInfoDto:"+ JSON.toJSONString(record));
            return null;
        }

    }
}

创建消费者consumer服务
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">
    <parent>
        <artifactId>springboot-dubbo</artifactId>
        <groupId>top.xzhand.springboot-dubbo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>consumer</artifactId>

<dependencies>

    <!--dubbo 依赖 -->
    <dependency>
        <groupId>com.alibaba.spring.boot</groupId>
        <artifactId>dubbo-spring-boot-starter</artifactId>
        <version>2.0.0</version>
    </dependency>
    <!-- zookeeper client依赖 -->
    <dependency>
        <groupId>com.101tec</groupId>
        <artifactId>zkclient</artifactId>
        <version>0.10</version>
        <exclusions>
            <exclusion>
                <artifactId>slf4j-log4j12</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <artifactId>provider-sdk</artifactId>
        <groupId>top.xzhand.springboot-dubbo</groupId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>
</project>

启动类

package top.xzhand;

import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDubboConfiguration
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class);
    }
}

application.yml 配置

server:
  port: 8082

spring:
  dubbo:
    application:            #应用配置,用于配置当前应用信息,不管该应用是提供者还是消费者。
      name: consumer
    registry:                 #注册中心配置,用于配置连接注册中心相关信息。
      address: zookeeper://localhost:2181
    protocol:     #协议配置,用于配置提供服务的协议信息,协议由提供方指定,消费方被动接受(订阅)。
      name: dubbo
      port: 20880
    consumer:
      check: false
    reference:
      loadbalance: roundrobin #轮询机制
      #loadbalance: random #随机机制
      #loadbalance: leastactive #最少活跃调用数机制

服务消费

package top.xzhand.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xzhand.dto.UserInfoDto;
import top.xzhand.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @RequestMapping("info")
    public String sayHi(Long id){
         UserInfoDto userInfo= userService.selectByPrimaryKey(id);
        return JSON.toJSONString(userInfo);
    }

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!