SpringBoot + Mybatis + Dubbo搭建流程

SpringBoot + Mybatis + Dubbo搭建流程

	tips:网上搜集了比较多的demo,并没有直接复用的版本。为了快速成型,这里引用了许多博主的测试demo,还请谅解。

github代码链接

一、环境准备:
  • JDK1.8
  • IntelliJ IDEA 2019.2
  • springBoot 1.5.1
  • mysql数据库
二、Zookeeper安装
  • 项目搭建已单机环境作为演示,zookeeper可安装在windows或Linux均可
  • 下载链接:https://zookeeper.apache.org/releases.html ,目前最新的稳定版本为 3.4.8 版本
  • 通用配置修改
    • 解压进入到conf目录,将zoo_sample.cfg文件拷贝一份,命名为zoo.cfg文件。zookeeper的运行依赖于这个zoo.cfg文件,下面是zoo.cfg文件的重要参数(必须配置)
      • ticktime:单位毫秒,设置客户端与zookeeper服务端的心跳时间,每隔ticktime,进行一次心跳检测
      • clientPort:zookeeper服务进程监听的TCP端口,默认为2181
      • dataDir:设置zookeeper存储快照的日志位置
  • 启动方式
    • windows:双击zkServer.bat
    • linux:./zkServer.sh start,启动完成后,可使用./zkServer.sh status命令查看是否启动成功
三、项目搭建

​ 传统的maven工程即可,也可以通过maven聚合工程,通过依赖传递完成项目搭建。这里使用最原始的方式记性搭建

  • dubbo-api:封装实体类和对外暴露的接口

    • 依赖以及目录结构在这里插入图片描述
    • 注意事项
      • 所有用户Dubbo接口的实体类必须实现Serializable接口在这里插入图片描述
      • 接口均为正常形式,无需添加任何注解在这里插入图片描述
      • 这里的依赖中只添加了lombok,如有需要还请自行添加
  • dubbo-server:Provider角色,通过zookeeper,向外暴露接口,供客户端调用

    目录结构在这里插入图片描述

    1. 依赖
    <?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">
        <groupId>com.dubbo.demo</groupId>
        <artifactId>dubbo-parent</artifactId>
        <version>1.0-SNAPSHOT</version>
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.1.RELEASE</version>
        </parent>
        <dependencies>
            <!--spring-boot-web依赖-->
            <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.3</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <!--zookeeper-->
            <dependency>
                <groupId>com.101tec</groupId>
                <artifactId>zkclient</artifactId>
                <version>0.2</version>
            </dependency>
            <dependency>
                <groupId>org.apache.zookeeper</groupId>
                <artifactId>zookeeper</artifactId>
                <version>3.4.5</version>
            </dependency>
        </dependencies>
    </project>
    
    1. mapper接口准备
    package com.dubbo.mapper;
    
    import com.dubbo.domain.Student;
    import com.dubbo.domain.StudentScore;
    import com.dubbo.domain.StudentScores;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    import java.util.Map;
    
    @Mapper
    public interface StudentMapper {
    
        Integer addStudent(Student student);
    
        Integer deleteStudentByName(String name);
    
        Integer deleteByStudent(Student student);
    
        Integer updateStudent(Student student);
    
        Student findStudentByName(String name);
    
        List<Student> findStudents();
    
        List<Student> findStudentByMap(Map<String, String> map);
    
        List<Student> findStudentByStudent(Student student);
    
        List<Student> findStudentByAgeAndSex(Integer age, String sex);
    
        List<StudentScores> findStudentScores();
    
        List<StudentScore> findStudentScore();
    }
    
    
    1. mapper.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.dubbo.mapper.StudentMapper">
        <!--
        执行增加操作的SQL语句
        1.id和parameterType 分别与StudentMapper接口中的addStudent方法的名字和 参数类型一致
        2.以#{studentName}的形式引用Student参数 的studentName属性,MyBatis将使用反射读取Student参数的此属性
        3.#{studentName}中studentName大小写敏感。引用其他的属性与此一致
        4.seGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键
        5.keyProperty="id"指定把获取到的主键值注入到Student的id属性
        -->
        <!-- 当表中字段名跟实体类字段名不一致 或 为了返回list类型 可以定义returnMap -->
        <resultMap id="studentMap" type="Student">
            <id column="student_id" property="studentId"/>
            <result column="name" property="name"/>
            <result column="age" property="age"/>
            <result column="sex" property="sex"/>
            <result column="hobbies" property="hobbies"/>
            <result column="address" property="address"/>
        </resultMap>
    
        <resultMap id="scoreResultMap" type="Score">
            <id column="score_id" property="scoreId"/>
            <result column="student_id" property="studentId"/>
            <result column="student_name" property="studentName"/>
            <result column="subject" property="subject"/>
            <result column="subject_score" property="subjectScore"/>
        </resultMap>
    
        <!--增删改查 开始-->
        <!--新增 1-->
        <insert id="saveStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="student_id">
            insert into t_student(name,age,sex,hobbies,address)
            values(#{name},#{age},#{sex},#{hobbies},#{address})
        </insert>
    
        <!--删除 1-->
        <delete id="deleteStudentByName" parameterType="String">
            delete from t_student where name=#{name}
        </delete>
        <!--删除 2-->
        <delete id="deleteByStudent" parameterType="Student">
            delete from t_student
            <where>
                1=1
                <if test="name != null and name != ''">
                    and name = #{name}
                </if>
                <if test="age != null and age != ''">
                    and age = #{age}
                </if>
                <if test="sex != null and sex != ''">
                    and sex=#{sex}
                </if>
                <if test="hobbies != null and hobbies != ''">
                    and hobbies=#{hobbies}
                </if>
                <if test="address != null and address != ''">
                    and address=#{address}
                </if>
            </where>
        </delete>
    
        <!--修改 1-->
        <update id="updateStudent" parameterType="Student">
            update t_student set
            <if test="age != null and age != ''">
                age = #{age},
            </if>
            <if test="sex != null and sex != ''">
                sex = #{sex},
            </if>
            <if test="hobbies != null and hobbies != ''">
                hobbies = #{hobbies},
            </if>
            <if test="address != null and address != ''">
                address = #{address}
            </if>
            where name=#{name}
        </update>
    
        <!--查询 1  -->
        <select id="findStudentByName" parameterType="String" resultMap="studentMap">
            SELECT * FROM t_student where name = #{name};
        </select>
    
        <!--查询 2 返回list的select语句,注意resultMap的值是指向前面定义好的 -->
        <select id="findStudents" resultMap="studentMap">
            select * from t_student
        </select>
    
        <!--查询 2 返回list的select语句,注意resultMap的值是指向前面定义好的 -->
        <select id="findScores" resultMap="scoreResultMap">
            select * from t_score
        </select>
    
        <!--查询 3 利用 hashMap 传递多个参数 -->
        <select id="findStudentByMap" parameterType="Map" resultType="Student">
            select * from t_student
            <where>
                1=1
                <if test="name != null and name != ''">
                    and name = #{name}
                </if>
                <if test="age != null and age != ''">
                    and age = #{age}
                </if>
                <if test="sex != null and sex != ''">
                    and sex=#{sex}
                </if>
                <if test="hobbies != null and hobbies != ''">
                    and hobbies=#{hobbies}
                </if>
                <if test="address != null and address != ''">
                    and address=#{address}
                </if>
            </where>
        </select>
    
        <!--查询 4 利用 hashMap 传递多个参数 -->
        <select id="findStudentByStudent" parameterType="Student" resultType="Student">
            select * from t_student
            <where>
                1=1
                <if test="name != null and name != ''">
                    and name = #{name}
                </if>
                <if test="age != null and age != ''">
                    and age = #{age}
                </if>
                <if test="sex != null and sex != ''">
                    and sex=#{sex}
                </if>
                <if test="hobbies != null and hobbies != ''">
                    and hobbies=#{hobbies}
                </if>
                <if test="address != null and address != ''">
                    and address=#{address}
                </if>
            </where>
        </select>
    
        <!--查询 5 Mybatis 自带的多个参数传递方法 这个时候没有 parameterType, 但用到了类似 #{param1} 类似的参数 -->
        <select id="findStudentByAgeAndSex" resultType="com.dubbo.domain.Student">
            select * from t_student where age = #{param1} and sex=#{param2}
        </select>
        <!--增删改查 结束-->
    
        <!--联合查询 开始-->
    
        <!--联合查询:studentScoreListResultMap-->
        <resultMap id="studentScoreListResultMap" type="com.dubbo.domain.StudentScores">
            <result column="name" jdbcType="VARCHAR" javaType="String" property="name"/>
            <result column="age" javaType="Integer" property="age"/>
            <result column="sex" javaType="String" property="sex"/>
            <collection property="scoreList" javaType="List" ofType="Score">
                <id column="scoreId" jdbcType="INTEGER" property="scoreId"/>
                <result property="studentId" column="student_id"/>
                <result property="studentName" column="student_name"/>
                <result property="subject" column="subject"/>
                <result property="subjectScore" column="subject_score"/>
            </collection>
        </resultMap>
    
        <!-- 联合查询 1 findStudentScoreList-->
        <select id="findStudentScores" parameterType="Integer" resultMap="studentScoreListResultMap">
            select
            a.student_id studentId,
            a.name name,
            a.age age,
            a.sex sex,
            b.score_id scoreId,
            b.student_id student_id,
            b.student_name student_name,
            b.subject subject,
            b.subject_score subject_score
            from t_student a
            left join t_score b
            on a.student_id=b.student_id
        </select>
    
        <!--联合查询:studentScoreResultMap-->
        <resultMap id="studentScoreResultMap" type="com.dubbo.domain.StudentScore">
            <result property="name" jdbcType="VARCHAR" javaType="String" column="name"/>
            <result property="age" column="age" jdbcType="VARCHAR" javaType="Integer"/>
            <result property="sex" column="sex" jdbcType="VARCHAR" javaType="String"/>
            <association property="score" javaType="com.dubbo.domain.Score">
                <id property="scoreId" column="score_id"/>
                <result property="studentId" column="student_id"/>
                <result property="studentName" column="student_name"/>
                <result property="subject" column="subject"/>
                <result property="subjectScore" column="subject_score"/>
            </association>
        </resultMap>
    
        <!-- 联合查询 2 findStudentScore-->
        <select id="findStudentScore" resultMap="studentScoreResultMap">
            select
            a.student_id studentId,
            a.name name,
            a.age age,
            a.sex sex,
            b.score_id scoreId,
            b.student_id student_id,
            b.student_name student_name,
            b.subject subject,
            b.subject_score subject_score
            from t_student a
            left join t_score b
            on a.student_id=b.student_id
            where b.subject = 'English'
            and a.name = b.student_name
        </select>
        <!-- 联合查询 结束 -->
    </mapper>
    
    
    <?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.dubbo.mapper.StudentMapper">
        <!--
        执行增加操作的SQL语句
        1.id和parameterType 分别与StudentMapper接口中的addStudent方法的名字和 参数类型一致
        2.以#{studentName}的形式引用Student参数 的studentName属性,MyBatis将使用反射读取Student参数的此属性
        3.#{studentName}中studentName大小写敏感。引用其他的属性与此一致
        4.seGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键
        5.keyProperty="id"指定把获取到的主键值注入到Student的id属性
        -->
        <!-- 当表中字段名跟实体类字段名不一致 或 为了返回list类型 可以定义returnMap -->
        <resultMap id="studentMap" type="Student">
            <id column="student_id" property="studentId"/>
            <result column="name" property="name"/>
            <result column="age" property="age"/>
            <result column="sex" property="sex"/>
            <result column="hobbies" property="hobbies"/>
            <result column="address" property="address"/>
        </resultMap>
    
        <resultMap id="scoreResultMap" type="Score">
            <id column="score_id" property="scoreId"/>
            <result column="student_id" property="studentId"/>
            <result column="student_name" property="studentName"/>
            <result column="subject" property="subject"/>
            <result column="subject_score" property="subjectScore"/>
        </resultMap>
    
        <!--增删改查 开始-->
        <!--新增 1-->
        <insert id="saveStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="student_id">
            insert into t_student(name,age,sex,hobbies,address)
            values(#{name},#{age},#{sex},#{hobbies},#{address})
        </insert>
    
        <!--删除 1-->
        <delete id="deleteStudentByName" parameterType="String">
            delete from t_student where name=#{name}
        </delete>
        <!--删除 2-->
        <delete id="deleteByStudent" parameterType="Student">
            delete from t_student
            <where>
                1=1
                <if test="name != null and name != ''">
                    and name = #{name}
                </if>
                <if test="age != null and age != ''">
                    and age = #{age}
                </if>
                <if test="sex != null and sex != ''">
                    and sex=#{sex}
                </if>
                <if test="hobbies != null and hobbies != ''">
                    and hobbies=#{hobbies}
                </if>
                <if test="address != null and address != ''">
                    and address=#{address}
                </if>
            </where>
        </delete>
    
        <!--修改 1-->
        <update id="updateStudent" parameterType="Student">
            update t_student set
            <if test="age != null and age != ''">
                age = #{age},
            </if>
            <if test="sex != null and sex != ''">
                sex = #{sex},
            </if>
            <if test="hobbies != null and hobbies != ''">
                hobbies = #{hobbies},
            </if>
            <if test="address != null and address != ''">
                address = #{address}
            </if>
            where name=#{name}
        </update>
    
        <!--查询 1  -->
        <select id="findStudentByName" parameterType="String" resultMap="studentMap">
            SELECT * FROM t_student where name = #{name};
        </select>
    
        <!--查询 2 返回list的select语句,注意resultMap的值是指向前面定义好的 -->
        <select id="findStudents" resultMap="studentMap">
            select * from t_student
        </select>
    
        <!--查询 2 返回list的select语句,注意resultMap的值是指向前面定义好的 -->
        <select id="findScores" resultMap="scoreResultMap">
            select * from t_score
        </select>
    
        <!--查询 3 利用 hashMap 传递多个参数 -->
        <select id="findStudentByMap" parameterType="Map" resultType="Student">
            select * from t_student
            <where>
                1=1
                <if test="name != null and name != ''">
                    and name = #{name}
                </if>
                <if test="age != null and age != ''">
                    and age = #{age}
                </if>
                <if test="sex != null and sex != ''">
                    and sex=#{sex}
                </if>
                <if test="hobbies != null and hobbies != ''">
                    and hobbies=#{hobbies}
                </if>
                <if test="address != null and address != ''">
                    and address=#{address}
                </if>
            </where>
        </select>
    
        <!--查询 4 利用 hashMap 传递多个参数 -->
        <select id="findStudentByStudent" parameterType="Student" resultType="Student">
            select * from t_student
            <where>
                1=1
                <if test="name != null and name != ''">
                    and name = #{name}
                </if>
                <if test="age != null and age != ''">
                    and age = #{age}
                </if>
                <if test="sex != null and sex != ''">
                    and sex=#{sex}
                </if>
                <if test="hobbies != null and hobbies != ''">
                    and hobbies=#{hobbies}
                </if>
                <if test="address != null and address != ''">
                    and address=#{address}
                </if>
            </where>
        </select>
    
        <!--查询 5 Mybatis 自带的多个参数传递方法 这个时候没有 parameterType, 但用到了类似 #{param1} 类似的参数 -->
        <select id="findStudentByAgeAndSex" resultType="com.dubbo.domain.Student">
            select * from t_student where age = #{param1} and sex=#{param2}
        </select>
        <!--增删改查 结束-->
    
        <!--联合查询 开始-->
    
        <!--联合查询:studentScoreListResultMap-->
        <resultMap id="studentScoreListResultMap" type="com.dubbo.domain.StudentScores">
            <result column="name" jdbcType="VARCHAR" javaType="String" property="name"/>
            <result column="age" javaType="Integer" property="age"/>
            <result column="sex" javaType="String" property="sex"/>
            <collection property="scoreList" javaType="List" ofType="Score">
                <id column="scoreId" jdbcType="INTEGER" property="scoreId"/>
                <result property="studentId" column="student_id"/>
                <result property="studentName" column="student_name"/>
                <result property="subject" column="subject"/>
                <result property="subjectScore" column="subject_score"/>
            </collection>
        </resultMap>
    
        <!-- 联合查询 1 findStudentScoreList-->
        <select id="findStudentScores" parameterType="Integer" resultMap="studentScoreListResultMap">
            select
            a.student_id studentId,
            a.name name,
            a.age age,
            a.sex sex,
            b.score_id scoreId,
            b.student_id student_id,
            b.student_name student_name,
            b.subject subject,
            b.subject_score subject_score
            from t_student a
            left join t_score b
            on a.student_id=b.student_id
        </select>
    
        <!--联合查询:studentScoreResultMap-->
        <resultMap id="studentScoreResultMap" type="com.dubbo.domain.StudentScore">
            <result property="name" jdbcType="VARCHAR" javaType="String" column="name"/>
            <result property="age" column="age" jdbcType="VARCHAR" javaType="Integer"/>
            <result property="sex" column="sex" jdbcType="VARCHAR" javaType="String"/>
            <association property="score" javaType="com.dubbo.domain.Score">
                <id property="scoreId" column="score_id"/>
                <result property="studentId" column="student_id"/>
                <result property="studentName" column="student_name"/>
                <result property="subject" column="subject"/>
                <result property="subjectScore" column="subject_score"/>
            </association>
        </resultMap>
    
        <!-- 联合查询 2 findStudentScore-->
        <select id="findStudentScore" resultMap="studentScoreResultMap">
            select
            a.student_id studentId,
            a.name name,
            a.age age,
            a.sex sex,
            b.score_id scoreId,
            b.student_id student_id,
            b.student_name student_name,
            b.subject subject,
            b.subject_score subject_score
            from t_student a
            left join t_score b
            on a.student_id=b.student_id
            where b.subject = 'English'
            and a.name = b.student_name
        </select>
        <!-- 联合查询 结束 -->
    </mapper>
    
    
    1. 实现类准备
    package com.dubbo.service.impl;
    
    import com.alibaba.dubbo.config.annotation.Service;
    import com.dubbo.domain.Student;
    import com.dubbo.domain.StudentScore;
    import com.dubbo.domain.StudentScores;
    import com.dubbo.mapper.StudentMapper;
    import com.dubbo.service.StudentService;
    
    import javax.annotation.Resource;
    import java.util.List;
    import java.util.Map;
    
    @Service
    public class StudentServiceImpl implements StudentService {
    
        @Resource
        private StudentMapper studentMapper;
    
        @Override
        public Integer addStudent(Student student) {
            return studentMapper.addStudent(student);
        }
    
        @Override
        public Integer deleteStudentByName(String name) {
            return studentMapper.deleteStudentByName(name);
        }
    
        @Override
        public Integer deleteByStudent(Student student) {
            return studentMapper.deleteByStudent(student);
        }
    
        @Override
        public Integer updateStudent(Student student) {
            return studentMapper.updateStudent(student);
        }
    
        @Override
        public Student findStudentByName(String name) {
            return studentMapper.findStudentByName(name);
        }
    
        @Override
        public List<Student> findStudents() {
            return studentMapper.findStudents();
        }
    
        @Override
        public List<Student> findStudentByMap(Map<String, String> map) {
            return studentMapper.findStudentByMap(map);
        }
    
        @Override
        public List<Student> findStudentByStudent(Student student) {
            return studentMapper.findStudentByStudent(student);
        }
    
        @Override
        public List<Student> findStudentByAgeAndSex(Integer age, String sex) {
            return studentMapper.findStudentByAgeAndSex(age,sex);
        }
    
        @Override
        public List<StudentScores> findStudentScores() {
            return studentMapper.findStudentScores();
        }
    
        @Override
        public List<StudentScore> findStudentScore() {
            return studentMapper.findStudentScore();
        }
    }
    
    
    1. springboot启动类准备
      • @ImportResource(“classpath:dubbo-server.xml”):引入dubbo配置文件
      • @MapperScan(value = “com.dubbo.mapper”):扫描mapper接口
    package com.dubbo.server;
    
    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-server.xml")
    @MapperScan(value = "com.dubbo.mapper")
    public class ServerStart {
        public static void main(String[] args) {
            SpringApplication.run(ServerStart.class);
        }
    }
    
    1. dubbo-server.xml,以下为参数分析
      • dubbo:application name=“dubbo-server” dubbo服务名称
      • dubbo:protocol name=“dubbo” port=“20880” 设置dubbo支持的协议和启动端口
      • dubbo:registry 注册中心
    <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">
        <!--设置应用名-->
        <dubbo:application name="dubbo-server"/>
        <!--设置RPC协议-->
        <dubbo:protocol name="dubbo" port="20880"/>
    
        <dubbo:registry address="zookeeper://zookeeper服务的ip:port" register="true" file="${user.home}/dubbo.cache"/>
        <!--设置注册中心地址zookeeper,register属性,默认是true,如果为true的化,就需要把发布的服务的服务地址注册到zookeeper
            如果为false,就不需要把服务的地址注册到zookeeper中
        -->
        <!--<dubbo:registry address="zookeeper://127.0.0.1:2181" register="false"/>-->
    
        <!--把具体的服务实现类交给spring容器管理-->
        <bean id="helloWorld" class="com.dubbo.service.impl.HelloWorldServiceImpl"/>
        <bean id="userService" class="com.dubbo.service.impl.UserServiceImpl"/>
        <bean id="studentService" class="com.dubbo.service.impl.StudentServiceImpl"/>
        <!--<bean id="userStudent" class="com.dubbo.service.impl.StudentServiceImpl"/>-->
    
        <dubbo:annotation package="com.dubbo"/>
    
        <!--发布服务-->
        <dubbo:service interface="com.dubbo.service.HelloWorldService" ref="helloWorld"/>
        <dubbo:service interface="com.dubbo.service.UserService" ref="userService"/>
        <dubbo:service interface="com.dubbo.service.StudentService" ref="studentService"/>
        <!--<dubbo:service interface="com.dubbo.service.StudentService" ref="userStudent"/>-->
    </beans>
    
    1. 启动配置
    server:
      port: 8999
    
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
        username: root
        password: root
    
    mybatis:
      mapper-locations: classpath:mapper/*.xml
      type-aliases-package: com.dubbo.domain
      configuration:
        cache-enabled: true
    
  • dubbo-client:consumer角色,调用provider暴露的接口

    • 目录结构[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O09lc7rm-1576480282729)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20191216145213866.png)]

    • 依赖:不需要连接数据库,其余与dubbo-server中的依赖一致

      <?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>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>1.5.1.RELEASE</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
      
          <groupId>com.dubbo.client</groupId>
          <artifactId>dubbo-client</artifactId>
          <version>1.0-SNAPSHOT</version>
      
          <dependencies>
              <dependency>
                  <groupId>com.dubbo.api</groupId>
                  <artifactId>dubbo-api</artifactId>
                  <version>1.0-SNAPSHOT</version>
              </dependency>
      
              <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.3</version>
                  <exclusions>
                      <exclusion>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring</artifactId>
                      </exclusion>
                  </exclusions>
              </dependency>
              <!--zookeeper-->
              <dependency>
                  <groupId>com.101tec</groupId>
                  <artifactId>zkclient</artifactId>
                  <version>0.2</version>
              </dependency>
              <dependency>
                  <groupId>org.apache.zookeeper</groupId>
                  <artifactId>zookeeper</artifactId>
                  <version>3.4.5</version>
              </dependency>
          </dependencies>
      </project>
      
    • 启动类

      package com.dubbo.client;
      
      import com.dubbo.domain.Student;
      import com.dubbo.domain.StudentScore;
      import com.dubbo.domain.StudentScores;
      import com.dubbo.domain.User;
      import com.dubbo.service.HelloWorldService;
      import com.dubbo.service.StudentService;
      import com.dubbo.service.UserService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.context.annotation.ComponentScan;
      import org.springframework.context.annotation.ImportResource;
      import org.springframework.web.bind.annotation.*;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      
      @SpringBootApplication
      @ImportResource("classpath:dubbo-client.xml")
      @ComponentScan(basePackages = {"com.dubbo.domain"})
      @RestController
      public class ClientStart {
      
          @Autowired
          private HelloWorldService helloWorldService;
      
          @Autowired
          private UserService userService;
      
          @Autowired
          private StudentService studentService;
      
          public static void main(String[] args) {
              SpringApplication.run(ClientStart.class);
          }
      
          @GetMapping("user")
          @ResponseBody
          public List<User> getUser(){
              return userService.findUser();
          }
      
      
          @PostMapping("/students")
          public Integer saveStudent(@RequestBody Student student) {
              Integer addNum = studentService.addStudent(student);
              return addNum;
          }
      
          @DeleteMapping("/students/{name}")
          public Integer deleteStudentByName(@PathVariable String name) {
              Integer deleteNum = studentService.deleteStudentByName(name);
              return deleteNum;
          }
      
          @DeleteMapping("/students")
          public Integer deleteStudentByStudent(@RequestBody Student student) {
              Integer deleteNum = studentService.deleteByStudent(student);
              return deleteNum;
          }
      
          @PutMapping("/students")
          public Integer updateStudent(@RequestBody Student student) {
              Integer updateNum = studentService.updateStudent(student);
              return updateNum;
          }
      
          @GetMapping("/students/{name}")
          public Student findStudentByName(@PathVariable String name) {
              Student student = studentService.findStudentByName(name);
              return student;
          }
      
          @GetMapping("/students")
          public List<Student> getStudentListByAgeAndSexAndHobbies() {
              List<Student> studentList = studentService.findStudents();
              return studentList;
          }
      
          @GetMapping("/students/map")
          public List<Student> findStudentByMap() {
              Map<String, String> map = new HashMap<String, String>();
              map.put("name", "Even");
              List<Student> studentList = studentService.findStudentByMap(map);
              return studentList;
          }
      
          @GetMapping("/students/{age}/{sex}")
          public List<Student> findStudentByAgeAndSex(@PathVariable Integer age, @PathVariable String sex) {
              List<Student> studentList = studentService.findStudentByAgeAndSex(age, sex);
              return studentList;
          }
      
          @GetMapping("/students/scores")
          public List<StudentScores> findStudentScores() {
              List<StudentScores> studentList = studentService.findStudentScores();
              return studentList;
          }
      
          @GetMapping("/students/score")
          public List<StudentScore> findStudentScore() {
              List<StudentScore> studentScores = studentService.findStudentScore();
              return studentScores;
          }
      
      }
      
      
    • dubbo-client.xml

      <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">
          <!--设置应用名-->
          <dubbo:application name="dubbo-client"/>
          <!--设置注册中心地址zookeeper-->
          <dubbo:registry address="zookeeper://106.13.111.184:2181"/>
      
          <dubbo:annotation package="com.dubbo.service"/>
          <!--引用服务-->
          <dubbo:reference interface="com.dubbo.service.HelloWorldService" id="helloWorldService"/>
          <dubbo:reference interface="com.dubbo.service.UserService" id="userService"/>
          <dubbo:reference interface="com.dubbo.service.StudentService" id="studentService" timeout="2000"/>
      </beans>
      
    • 启动配置

      server.port=9090
      
测试结果

在这里插入图片描述
在这里插入图片描述

五、踩坑日记
  1. springBoot和Mybatis版本不兼容问题:

    例如上述项目依赖于springBoot 1.5.1 ,对应org.mybatis.spring.boot版本为1.1及以下

    如果使用springBoot 2.x,对应org.mybatis.spring.boot的版本应为1.3.x

  2. controller中使用@Reference注解,注入service为null

    根本原因为dubbo接口会随着spring容器加载时创建,此为父类容器,与springmvc加载容器互不相识,所以在controller中,注入dubbo接口变得不现实。因此目前该项目中controller注入方式为@Autowired

    具体解决方案还待学习了解,一下为大神的解析思路:https://blog.csdn.net/zhou_java_hui/article/details/53039491

  3. 其余的细节问题,比如拼写等小错误这些就全靠大家的视力水平了。我在这里就不献丑了。

非常感谢您看到这里,如果可以的话,在github来个star,么么么,加粗加大!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值