搭建SpringBoot+dubbo+zookeeper+maven框架(一)

這幾天項目還沒來,因此就本身試着參考網上的一些資料,搭建了一個SpringBoot+dubbo+zookeeper+maven框架,網上參考的不少資料照着他們一步一步搭建,最後不少都運行不通,非常鬱悶,最後本身在總結了他們以後本身搭建了一個,項目的源碼我會附在文章的最後,而且後期還會繼續優化,但願對你們能有所幫助。java

參考的文章地址:mysql

https://www.jianshu.com/p/2b128ac75e95web

https://blog.csdn.net/hjl021/article/details/79192115#commentBoxspring

 

既然要用到zookeeper,咱們確定要在本身本地下載一個zookeeper,這個網上一搜一大堆,這裏我就很少說了。sql

首先新建一個maven項目,項目目錄以下圖所示。

再在該父項目中建立3個module,分別是:provider(服務端)、customer(消費端)、common(存放全部接口和實體類)數據庫

咱們在父項目的pom.xml文件中添加須要的jar包。apache

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

   <groupId>com.lj</groupId>
   <artifactId>springboot-mybatis-dubbo-zookeeper</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>springboot-mybatis-dubbo-zookeeper</name>
   <description>Demo project for Spring Boot</description>

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

   <modules>
      <!-- 服務消費者工程 -->
      <module>customer</module>
      <!--  服務提供者工程-->
      <module>provider</module>
      <!-- 主要放實體、接口、也能夠放一些公用的工具類工程-->
      <module>common</module>
   </modules>

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

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
            <version>${spring-boot.version}</version>
      </dependency>

      <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>

        <!-- 使用lombok實現JavaBean的get、set、toString、hashCode、equals等方法的自動生成  -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- Dubbo依賴 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>${dubbo.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

         <!--zookeeper的客戶端依賴-->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>${zkclient.version}</version>
        </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
               <encoding>UTF-8</encoding>
            </configuration>

         </plugin>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
               <encoding>UTF-8</encoding>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>
 
 

 至此,父項目就能夠不用管它了。springboot

 

接着咱們再來搭建common模塊:mybatis

首先是pom.xml,以下:app

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

   <groupId>com.lj</groupId>
   <artifactId>common</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

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

   <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>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

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

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

   </dependencies>

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

</project>

 

再在common下建立domin(放實體類)和service(放接口)兩個文件夾

在domin中建立User.java實體類(這裏有一個坑,就是該實體類必定要實現java.io.Serializable這個接口,不然會報錯這是由於一個類只有實現了Serializable接口,它的對象纔是可序列化的。若是要序列化某些類的對象,這些類就必須實現Serializable接口。而實際上,Serializable是一個空接口,沒有什麼具體內容,它的目的只是簡單的標識一個類的對象能夠被序列化。這是我踩過的一個坑,你們能夠試着把implements Serializable 去掉,確定會報錯的,報錯中會有一句Serialized class com.yykj.mall.dto.ProductListItemDTO must implement java.io.Serializable):

package com.lj.common.domin;

import java.io.Serializable;
import java.util.PrimitiveIterator;

/**
 * Created with IntelliJ IDEA.
 * User: gaopeng
 * Date: 2018/8/28 0028
 * Time: 18:00
 * Description:
 */
public class User implements Serializable{
    private int id;

    private  String name;

    private  int age;

    private String sex;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

 

 在service中建立UserService接口:

package com.lj.common.service;

import com.lj.common.domin.User;

/**
* @author gaopeng
* @date 2018/8/28 0028 18:04
*/
public interface UserService {
    User findUser();
}

 

 application.properties這個文件是空的,你們不用理會,此時,common模塊基本完成。

 

接下來就是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">
   <modelVersion>4.0.0</modelVersion>

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

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

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

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

   <dependencies>
      <dependency>
         <groupId>com.lj</groupId>
         <artifactId>common</artifactId>
         <version>0.0.1-SNAPSHOT</version>
      </dependency>

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

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


      <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>dubbo</artifactId>
         <version>2.5.5</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
      </dependency>

      <!--zookeeper的客戶端依賴-->
      <dependency>
         <groupId>com.101tec</groupId>
         <artifactId>zkclient</artifactId>
         <version>${zkclient.version}</version>
      </dependency>
      
      <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>1.3.1</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-jdbc</artifactId>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>5.1.35</version>
      </dependency>
      <!-- alibaba的druid數據庫鏈接池 -->
      <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>druid</artifactId>
         <version>1.0.11</version>
      </dependency>
   </dependencies>

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

</project>
 
 

 


咱們這邊使用springboot,由於基本上都封裝好了,配置就很簡單了。咱們先新增一個application.yml,具體配置以下,這邊直接將mybatis的配置寫在配置文件裏了,就不須要像ssm同樣須要xml文件配置了。application.yml:
server:
  port: 8082
  servlet:
    context-path: /
spring:
 datasource:
        name: test
        url: jdbc:mysql://127.0.0.1:3306/springdb
        username: root
        password: root
        # 使用druid數據源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
        mybatis:
          type-aliases-package:  domain

 

同時,咱們須要在項目中配置dubbo,讓該項目成爲提供者。
SpringBoot_Dubbo_Provider 的 spring-dubbo.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: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://code.alibabatech.com/schema/dubbo
       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <dubbo:application name="provider"/>
    <!-- 註冊中心的ip地址 -->
    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
    <!-- 掃描註解包路徑,多個包用逗號分隔,不填pacakge表示掃描當前ApplicationContext中全部的類 -->
    <dubbo:annotation package="service.impl"/>

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

    <!-- service implementation, as same as regular local bean -->
    <bean id="userService" class="com.lj.provider.service.impl.UserImpl"/>
    <!-- declare the service interface to be exported -->
    <dubbo:service interface="com.lj.common.service.UserService" ref="userService"/>
</beans>

 

 
 

Springboot是使用類來做爲啓動器的,因此咱們啓動添加一個啓動器ProviderApplication.java,在啓動器中將dubbo的配置文件引用,而且去掃描mapper包。

SpringBoot_Dubbo_Provider ProviderApplication.java:

package com.lj.provider;

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

import java.io.IOException;

@SpringBootApplication
@ImportResource({"classpath:spring-dubbo.xml"})
@MapperScan("mapper")
public class ProviderApplication {

   public static void main(String[] args) throws IOException {
      SpringApplication.run(ProviderApplication.class, args);
      System.out.println("服務端啓動成功!!!");
      try {
         System.in.read();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

 

一樣咱們也要爲這個項目寫一個啓動器。在啓動器中加載dubbo配置文件 。這裏提供者和消費者兩個項目不能使用相同的端口號,因此消費者這邊端口我使用的是8081 提供者爲8082。也就是在provider中的application.properties中寫上server.port=8082,在customer中的application.properties中寫上server.port=8081
 

   而後建立mapper文件夾,在裏面建立UserMapper接口,接口內容以下:

package com.lj.provider.mapper;

import com.lj.common.domin.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Results(id = "userMap", value = {
            @Result(column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "age", property = "age"),
            @Result(column = "sex", property = "sex")})
    @Select("SELECT * FROM u_user")
    List<User> getAll();

    @Select("SELECT * FROM u_user t WHERE t.id = #{id}")
    @ResultMap("userMap")
    User getOne(Long id);
}

 

 再在service文件夾下的Impl中編寫UserImpl接口的實現類,內容以下:

package com.lj.provider.service.impl;

import com.lj.common.domin.User;
import com.lj.common.service.UserService;
import com.lj.provider.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: gaopeng
 * Date: 2018/8/28 0028
 * Time: 20:02
 * Description:
 */
@Service(version = "1.0.0")
public class UserImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUser() {
        return userMapper.getOne(1l);
    }
}

 

 此時provider服務端就編寫完畢了。

接下來就是編寫customer消費端了:

 

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>com.lj</groupId>
   <artifactId>customer</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

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

   <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>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
        <zkclient.version>0.10</zkclient.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>com.lj</groupId>
         <artifactId>common</artifactId>
         <version>0.0.1-SNAPSHOT</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>

      <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>dubbo</artifactId>
            <version>2.5.5</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--zookeeper的客戶端依賴-->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>${zkclient.version}</version>
        </dependency>
   </dependencies>

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


</project>

 

 接下來要爲dubbo編寫xml配置文件,在resource文件夾中新建spring-dubbo.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: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://code.alibabatech.com/schema/dubbo
       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <dubbo:application name="consumer"/>
    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
    <dubbo:protocol name="dubbo" port="20880"/>
    <dubbo:reference id="userService" check="false" interface="com.lj.common.service.UserService"/>
    <dubbo:annotation package="controller"/>
</beans>

 


而後就是編寫controller了,建立UserController.java文件,調用common中的UserService接口,這裏是用註解的形式注入的
package com.lj.customer.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lj.common.domin.User;
import com.lj.common.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: gaopeng
 * Date: 2018/8/28 0028
 * Time: 17:45
 * Description:
 */
@RestController
public class UserController {
    @Resource
    @Reference(version = "1.0.0")
    private UserService userService;

    @GetMapping("getUser")
    public User user(){
        System.out.println("進來了!!!!!!!!!!!!!!!!");
        System.out.println(userService.hashCode()+"!!!!!!!!!!!!!!!!");
        return userService.findUser();
    }
}

 

再給customer消費端寫一個啓動類CustomerApplication:
package com.lj.customer;

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

@SpringBootApplication
@ImportResource({"classpath:spring-dubbo.xml"})
public class CustomerApplication {

   public static void main(String[] args) {
      SpringApplication.run(CustomerApplication.class, args);
        System.out.println("消費端啓動成功!!!");
   }
}

 

這樣,全部的配置咱們都完成了,這裏,我就簡單的從數據庫根據ID查一個user信息爲例子。
首先建立一個u_user表:
CREATE TABLE `u_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
  `name` varchar(256) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年齡',
  `sex` varchar(4) DEFAULT NULL COMMENT '性別',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

 


這時再前後啓動provider和customer,能夠在dubbo可視化界面中看到項目的生產者和消費者都啓動成功了:

再在postman中發送請求:

能夠看到,數據已經從數據庫中查出來了,至此,SpringBoot+dubbo+zookeeper+maven框架搭建完畢!

這是下載該項目框架demo的網址:https://download.csdn.net/download/weixin_38340967/10634074

後期還會對該框架添加分頁,事務,代碼自動生成等功能,但願各位小夥伴們的支持,謝謝!!!

未完待續。。。

相關文章
相關標籤/搜索