springboot多模塊開發以及整合dubbo\zookeeper進行服務管理

  以前研究了springboot單工程的使用,參考git地址:https://github.com/qiao-zhi/springboot-ssmhtml

  下面研究springboot多模塊開發的過程。java

1.模塊簡介:

springboot-ssm-soa:  父工程mysql

springboot-ssm-common:   公共類工程,包括工具類等(其實這一模塊還能夠再分)
springboot-ssm-bean     實體類工程
springboot-ssm-service     服務層接口(不包括實現)
springboot-ssm-dao          dao層接口與實現
springboot-ssm-service-provider    服務層實現
springboot-ssm-web    控制層與頁面以及靜態資源git

 2.模塊詳細介紹

 2.1  springboot-ssm-soa 父工程

 pom文件:定義公用的jar包以及引入相應模塊github

<?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>cn.qlq</groupId>
    <artifactId>springboot-ssm-soa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>springboot-ssm-common</module>
        <module>springboot-ssm-bean</module>
        <module>springboot-ssm-service</module>
        <module>springboot-ssm-dao</module>
        <module>springboot-ssm-service-provider</module>
        <module>springboot-ssm-web</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

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

        <!--springboot單元測試 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--熱加載 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!-- spring-boot整合mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!-- 使用事務須要引入這個包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- 引入 spring aop 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!-- 引入 redis 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!--pagehelper插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>

        <!-- 引入 freemarker 模板依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- 引入 thymeleaf 模板依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- commons工具包 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- 阿里的fastjson用於手動轉JSON -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>
    </dependencies>

    <distributionManagement>
        <repository>
            <id>releases</id>
            <url>http://192.168.0.133:8081/repository/maven-releases/</url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <url>http://192.168.0.133:8081/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>

    <build>
        <!-- 配置了不少插件 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

   注意:多模塊項目僅僅須要在啓動類所在的模塊添加打包插件便可!不要在父類添加打包插件,由於那樣會致使所有子模塊都使用spring-boot-maven-plugin的方式來打包(例如BOOT-INF/com/xxx/xx)。web

2.2  springboot-ssm-bean 子項目

   這個模塊存放的是項目的實體類。redis

pom文件以下:spring

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.qlq</groupId>
        <artifactId>springboot-ssm-soa</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>cn.qlq</groupId>
    <artifactId>springboot-ssm-bean</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-ssm-bean</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
    </dependencies>
</project>

2.3  springboot-ssm-common 子項目

   存放系統的工具類以及一些其餘配置信息,其實這一模塊還能夠再分。sql

pom以下:數據庫

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.qlq</groupId>
        <artifactId>springboot-ssm-soa</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>cn.qlq</groupId>
    <artifactId>springboot-ssm-common</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-ssm-common</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>cn.qlq</groupId>
            <artifactId>springboot-ssm-bean</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

2.4  springboot-ssm-dao 子項目

   dao模塊,用於寫dao層接口和mapp的xml實現。

pom以下:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>cn.qlq</groupId>
    <artifactId>springboot-ssm-soa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>cn.qlq</groupId>
  <artifactId>springboot-ssm-dao</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot-ssm-dao</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
      <dependency>
          <groupId>cn.qlq</groupId>
          <artifactId>springboot-ssm-bean</artifactId>
          <version>0.0.1-SNAPSHOT</version>
      </dependency>
  </dependencies>
</project>

applications-dao.properties文件內容以下:

############################################################ # # Mybatis settings # ############################################################ #jiazai mybatis peizhiwenjian(**表明任意目錄,*表明任意多個字符) mybatis.mapper-locations = classpath:mapper/**/*Mapper.xml mybatis.config-location = classpath:mybatis/SqlMapConfig.xml mybatis.type-aliases-package = cn.qlq.bean ############################################################ # # datasource settings # ############################################################ spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = 123456

2.5  springboot-ssm-service 子項目

   service層接口,不寫實現,實現類單獨抽取是爲了發佈dubbo服務。

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>cn.qlq</groupId>
    <artifactId>springboot-ssm-soa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>cn.qlq</groupId>
  <artifactId>springboot-ssm-service</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot-ssm-service</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
      <dependency>
          <groupId>cn.qlq</groupId>
          <artifactId>springboot-ssm-dao</artifactId>
          <version>0.0.1-SNAPSHOT</version>
      </dependency>
  </dependencies>
</project>

2.6  springboot-ssm-service-provider 子項目

   service接口實現。單獨抽取是爲了發佈dubbo服務。

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.qlq</groupId>
        <artifactId>springboot-ssm-soa</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>cn.qlq</groupId>
    <artifactId>springboot-ssm-service-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-ssm-service-provider</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>cn.qlq</groupId>
            <artifactId>springboot-ssm-service</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>cn.qlq</groupId>
            <artifactId>springboot-ssm-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

2.7  springboot-ssm-web 子項目

   controller層以及頁面都在這一模塊。

pom文件:

  引入spring-boot-maven-plugin插件是爲了打包、引入內嵌的tomcat是爲了打包爲jar包能夠直接運行,而且pom文件中打包方式爲jar包。

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.qlq</groupId>
        <artifactId>springboot-ssm-soa</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>springboot-ssm-web</groupId>
    <artifactId>springboot-ssm-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-ssm-web</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>cn.qlq</groupId>
            <artifactId>springboot-ssm-service-provider</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <!-- 設置Tomcat打包的時候不打包下面配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!-- <scope>provided</scope> -->
        </dependency>
    </dependencies>

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

 

applications.properties

  spring.profiles.active=dao是爲了引入dao模塊的applications-dao.properties文件。

###引入多個properties文件配置 spring.profiles.active=dao ############################################################ # # 日誌相關配置(默認集成的有slf4j,Logback等) # ############################################################ #指定配置文件的位置,只能是xml或者groovy結尾 #logging.config=classpath:logback.xml #默認的日誌級別 logging.level.root=INFO # mapper 接口所在的包設置爲 debug logging.level.cn.qlq.mapper=DEBUG #生成日誌文件的位置 logging.file=G:/springboot.log #生成日誌文件的目錄,名稱默認爲spring.log #logging.path=e:/ #指定日誌的格式 #logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %clr(%logger){cyan} %clr(%msg%n){green} #logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n ############################################################ # # Server 服務端相關配置 # ############################################################ # 配置api端口號 server.port=8088 # 配置context-path, 通常來講這個配置在正式發佈的時候不配置 server.context-path=/MySpringboot server.serverlet-path=*.do,*.action # 錯誤頁,指定發生錯誤時,跳轉的URL --> BasicErrorController #server.error.path=/error # session最大超時時間(分鐘),默認爲30分鐘 server.session-timeout=60 # 該服務綁定IP地址,啓動服務器時如本機不是該IP地址則拋出異常啓動失敗, # 只有特殊需求的狀況下才配置, 具體根據各自的業務來設置 #server.address=192.168.1.2 ############################################################ # Server - tomcat 相關經常使用配置 ############################################################ # tomcat最大線程數, 默認爲200 #server.tomcat.max-threads=250 # tomcat的URI編碼 server.tomcat.uri-encoding=UTF-8 # 存放Tomcat的日誌、Dump等文件的臨時文件夾,默認爲系統的tmp文件夾 #(如:C:%users\Shanhy\AppData\Local\Temp) #server.tomcat.basedir=H:/springboot-tomcat-tmp # 打開Tomcat的Access日誌,並能夠設置日誌格式的方法: #server.tomcat.access-log-enabled=true #server.tomcat.access-log-pattern= # accesslog目錄,默認在basedir/logs #server.tomcat.accesslog.directory= # 日誌文件目錄 #logging.path=H:/springboot-tomcat-tmp # 日誌文件名稱,默認爲spring.log #logging.file=myapp.log ############################################################ # # thymeleaf 靜態資源配置 # ############################################################ spring.thymeleaf.prefix=classpath:/templates/thymeleaf/x-admin/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html # 關閉緩存, 即時刷新, 上線生產環境須要改成true spring.thymeleaf.cache=false #關閉thymeleaf引擎 #spring.thymeleaf.enabled=false spring.messages.basename=i18n/messages spring.messages.cache-seconds=3600 spring.messages.encoding=UTF-8 spring.jackson.date-format=yyyy-MM-dd spring.jackson.time-zone=GMT+8 spring.jackson.serialization.write-dates-as-timestamps=false ############################################################ # # REDIS 配置 # ############################################################ # Redis數據庫索引(默認爲0) spring.redis.database=1 # Redis服務器地址 spring.redis.host=localhost # Redis服務器鏈接端口 spring.redis.port=6379 # Redis服務器鏈接密碼(默認爲空) spring.redis.password= # 鏈接池最大鏈接數(使用負值表示沒有限制) spring.redis.pool.max-active=1000 # 鏈接池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.pool.max-wait=-1 # 鏈接池中的最大空閒鏈接 spring.redis.pool.max-idle=10 # 鏈接池中的最小空閒鏈接 spring.redis.pool.min-idle=2 # 鏈接超時時間(毫秒) spring.redis.timeout=0

 

MySpringBootApplication.java是運行類的入口:

package cn.qlq; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan("cn") // Servlet、Filter、Listener能夠直接經過@WebServlet、@WebFilter、@WebListener註解自動註冊,無需其餘代碼。
public class MySpringBootApplication { public static void main(String[] args) { // 入口運行類
        SpringApplication.run(MySpringBootApplication.class, args); } }

 

  其運行方式依然是點擊上面主類運行便可。

  打包方式也是同普通的springboot項目,只不過打包方式選擇在web層進行打包,因此web層的pom文件加入了spring-boot-maven-plugin插件與內置的tomcat。參考:https://www.cnblogs.com/qlqwjy/p/8548690.html

 

注意:

  上面多個模塊之間相互依賴,因此要先執行maven install上傳到本地倉庫,而後對本地倉庫從新創建索引引入對應的jar包便可。並且父工程不能夠引入spring-boot-maven-plugin插件,不然會影響打的jar包。(咱們知道springboot打的jar包是其特有的目錄結構,會加入其自身的一些類)

        

 

git地址:https://github.com/qiao-zhi/springboot-ssm-soa

原來沒有分模塊的項目地址:https://github.com/qiao-zhi/springboot-ssm

項目須要的sql腳本也能夠在沒有分模塊的git地址進行下載。

 

======對service的實現進行dubbo發佈服務到zookeeper====

  上面已經對普通的springboot項目進行改造完成。在此基礎上對springboot-ssm-service-provider模塊進行改造,將服務發佈到zookeeper中以及web層從dubbo消費服務。前期zookeeper的集羣搭建以及啓動zookeeper參考以前的zookeeper學習。

   只是在上面的基礎上稍做修改。

1.父工程pom.xml文件增長dubbo-spring-boot-starter以及zkclient依賴

<!-- 引入dubbo-spring-boot-starter以及zkclient依賴 -->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.9</version>
        </dependency>

 

 2.bean工程的全部class都是些Serializable接口

 3.commons工程基本不變

 4.dao工程也基本不變

 5.service工程的UserService增長下面方法

public PageInfo<User> getPageInfoUsers(Map condition);

 

6.springboot-ssm-service-provider模塊修改以下

1.引入applications.properties文件 --引入dubbo服務相關配置與引入dao層的properties配置文件

###引入多個properties文件配置 spring.profiles.active=dao ############################################################ # # DUBBO相關配置 # ############################################################ #當前服務/應用名稱 spring.dubbo.application.name=provider #註冊中心的協議和地址 spring.dubbo.server=true spring.dubbo.registry=zookeeper://127.0.0.1:2181
#通訊規則(通訊協議和接口) spring.dubbo.protocol.name=dubbo spring.dubbo.protocol.port=20880

 

2.UserServiceImpl修改成以下:

  經過@com.alibaba.dubbo.config.annotation.Service(version = "1.0.0")發佈dubbo服務;實現getPageInfoUsers方法(支持pagehelper分頁)

package cn.qlq.service.impl.user; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.qlq.bean.user.User; import cn.qlq.bean.user.UserExample; import cn.qlq.bean.user.UserExample.Criteria; import cn.qlq.mapper.user.UserMapper; import cn.qlq.service.user.UserService; @Service @com.alibaba.dubbo.config.annotation.Service(version = "1.0.0") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; public List<User> findAllUser() { UserExample userExample = new UserExample(); List<User> list = userMapper.selectByExample(userExample); return list; } @Override public void addUser(User user) { userMapper.insert(user); } @Override public List<User> getUsers(Map condition) { UserExample userExample = new UserExample(); if (StringUtils.isNotBlank(MapUtils.getString(condition, "username"))) { Criteria createCriteria = userExample.createCriteria(); createCriteria.andUsernameLike("%" + MapUtils.getString(condition, "username") + "%"); } List<User> list = userMapper.selectByExample(userExample); return list; } @Override public void deleteUser(int id) { userMapper.deleteByPrimaryKey(id); } @Override public User getUser(int id) { return userMapper.selectByPrimaryKey(id); } @Override public void updateUser(User user) { userMapper.updateByPrimaryKeySelective(user); } @Override public PageInfo<User> getPageInfoUsers(Map condition) { PageHelper.startPage(MapUtils.getIntValue(condition, "pageNum"), MapUtils.getIntValue(condition, "pageSize")); UserExample userExample = new UserExample(); if (StringUtils.isNotBlank(MapUtils.getString(condition, "username"))) { Criteria createCriteria = userExample.createCriteria(); createCriteria.andUsernameLike("%" + MapUtils.getString(condition, "username") + "%"); } List<User> list = userMapper.selectByExample(userExample); return new PageInfo<User>(list); } }

 

3.編寫DubboServiceProvider.java發佈dubbo服務

package cn.qlq.service.impl; import java.util.concurrent.CountDownLatch; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration; @SpringBootApplication @EnableDubboConfiguration @MapperScan("cn.qlq.mapper") public class DubboServiceProvider { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); // 入口運行類
        SpringApplication.run(DubboServiceProvider.class, args); countDownLatch.await(); } }

7.  springboot-ssm-web以下修改

以UserController爲例子:

  @Reference(version = "1.0.0")是從zookeeper註冊中心消費服務

package cn.qlq.controller; import java.util.Date; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.dubbo.config.annotation.Reference; import com.github.pagehelper.PageInfo; import cn.qlq.annotation.MyLogAnnotation; import cn.qlq.bean.user.User; import cn.qlq.service.user.UserService; import cn.qlq.utils.JSONResultUtil; import cn.qlq.utils.ValidateCheck; @Controller /** 自動返回的是json格式數據 ***/ @RequestMapping("user") public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Reference(version = "1.0.0") private UserService userService; /** * 添加user * * @param user * springMVC自動映射的實體 * @return
     */ @RequestMapping("addUser") @ResponseBody public JSONResultUtil addUser(User user) { user.setCreatetime(new Date()); logger.info("user -> {}", user); userService.addUser(user); return JSONResultUtil.ok(); } /** * 分頁查詢user * * @param condition * @return
     */ @RequestMapping("getUsers") // @Cacheable(value = "usersCache", keyGenerator = "keyGenerator") //
    // 在redis中開啓key爲findAllUser開頭的存儲空間。key和keyGenerator只能使用一個
    @MyLogAnnotation(operateDescription = "分頁查詢用戶") @ResponseBody public PageInfo<User> getUsers(@RequestParam Map condition) { if (ValidateCheck.isNull(MapUtils.getString(condition, "pageNum"))) { // 若是不爲空的話改變當前頁號
            condition.put("pageNum", 1); } if (ValidateCheck.isNull(MapUtils.getString(condition, "pageSize"))) { // 若是不爲空的話改變當前頁大小
            condition.put("pageSize", 6); } PageInfo<User> pageInfo = userService.getPageInfoUsers(condition); return pageInfo; } /** * 刪除user * * @param user * springMVC自動映射的實體 * @return
     */ @RequestMapping("deleteUser") @ResponseBody public JSONResultUtil deleteUser(int id) { userService.deleteUser(id); return JSONResultUtil.ok(); } /** * 跳轉打修改用戶頁面 * * @param id * @return
     */ @RequestMapping("updateUser") public String updateUser(int id, ModelMap map) { User user = userService.getUser(id); map.addAttribute("user", user); return "updateUser"; } /** * 添加user * * @param user * springMVC自動映射的實體 * @return
     */ @RequestMapping("doUpdateUser") @ResponseBody public JSONResultUtil doUpdateUser(User user) { logger.info("user -> {}", user); userService.updateUser(user); return JSONResultUtil.ok(); } }

 

pom.xml依賴於接口,不依賴實現類。

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.qlq</groupId>
        <artifactId>springboot-ssm-soa</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>springboot-ssm-web</groupId>
    <artifactId>springboot-ssm-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-ssm-web</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- 設置Tomcat打包的時候不打包下面配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!-- <scope>provided</scope> -->
        </dependency>
        <dependency>
            <groupId>cn.qlq</groupId>
            <artifactId>springboot-ssm-service</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>cn.qlq</groupId>
            <artifactId>springboot-ssm-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

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

8.測試:

(1) 先啓動springboot-ssm-service-provider模塊的生產服務類DubboServiceProvider,啓動後從dubbo-admin查看以下:

(2)啓動web模塊進行訪問以後查看消費者:

 

  至此基於dubbo服務的SOA搭建基本完成。

下面總結本身在集成dubbo服務時遇到的坑。

1.服務生產者類直接調用的時候報錯找不到mapper,也就是沒有掃描mapper包,所以在啓動類頭上增長註解以下:

package cn.qlq.service.impl; import java.util.concurrent.CountDownLatch; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration; @SpringBootApplication @EnableDubboConfiguration @MapperScan("cn.qlq.mapper") public class DubboServiceProvider { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); // 入口運行類
        SpringApplication.run(DubboServiceProvider.class, args); countDownLatch.await(); } }

 

 2.dubbo服務整合pageHelper分頁的時候原來是在controller進行分頁,dubbo服務從註冊中心獲取以後分頁無效,所以修改成將條件傳到serivce層進行分頁

原來的controller:

@RequestMapping("getUsers") // @Cacheable(value = "usersCache", keyGenerator = "keyGenerator") // 在redis中開啓key爲findAllUser開頭的存儲空間。key和keyGenerator只能使用一個
    @MyLogAnnotation(operateDescription = "分頁查詢用戶") @ResponseBody public PageInfo<User> getUsers(@RequestParam Map condition) { int pageNum = 1; if (ValidateCheck.isNotNull(MapUtils.getString(condition, "pageNum"))) { // 若是不爲空的話改變當前頁號
            pageNum = Integer.parseInt(MapUtils.getString(condition, "pageNum")); } int pageSize = DefaultValue.PAGE_SIZE; if (ValidateCheck.isNotNull(MapUtils.getString(condition, "pageSize"))) { // 若是不爲空的話改變當前頁大小
            pageSize = Integer.parseInt(MapUtils.getString(condition, "pageSize")); } // 開始分頁
 PageHelper.startPage(pageNum, pageSize); List<User> users = new ArrayList<User>(); try { users = userService.getUsers(condition); } catch (Exception e) { logger.error("getUsers error!", e); } PageInfo<User> pageInfo = new PageInfo<User>(users); return pageInfo; }

原來的serviceImpl:

 @Override public List<User> getUsers(Map condition) { UserExample userExample = new UserExample(); if (StringUtils.isNotBlank(MapUtils.getString(condition, "username"))) { Criteria createCriteria = userExample.createCriteria(); createCriteria.andUsernameLike("%" + MapUtils.getString(condition, "username") + "%"); } List<User> list = userMapper.selectByExample(userExample); return list; }

 

 

整合dubbo服務的controller

@RequestMapping("getUsers") // @Cacheable(value = "usersCache", keyGenerator = "keyGenerator") //
    // 在redis中開啓key爲findAllUser開頭的存儲空間。key和keyGenerator只能使用一個
    @MyLogAnnotation(operateDescription = "分頁查詢用戶") @ResponseBody public PageInfo<User> getUsers(@RequestParam Map condition) { if (ValidateCheck.isNull(MapUtils.getString(condition, "pageNum"))) { // 若是不爲空的話改變當前頁號
            condition.put("pageNum", 1); } if (ValidateCheck.isNull(MapUtils.getString(condition, "pageSize"))) { // 若是不爲空的話改變當前頁大小
            condition.put("pageSize", 6); } PageInfo<User> pageInfo = userService.getPageInfoUsers(condition); return pageInfo; }

整合dubbo的serviceImpl

 @Override public PageInfo<User> getPageInfoUsers(Map condition) { PageHelper.startPage(MapUtils.getIntValue(condition, "pageNum"), MapUtils.getIntValue(condition, "pageSize")); UserExample userExample = new UserExample(); if (StringUtils.isNotBlank(MapUtils.getString(condition, "username"))) { Criteria createCriteria = userExample.createCriteria(); createCriteria.andUsernameLike("%" + MapUtils.getString(condition, "username") + "%"); } List<User> list = userMapper.selectByExample(userExample); return new PageInfo<User>(list); }
相關文章
相關標籤/搜索