1. 程式人生 > >spring cloud config--client

spring cloud config--client

概述

之前我們簡單的搭建了一個單點的config-server服務,實現配置檔案的統一管理,本次文章將實現config-client是如何從config-server中獲取到統一配置檔案資訊的

1.建立springcloud--ssmServer服務

此服務是之前的springBoot繼承了mybatis和springMvc等框架的完整專案,這裡用來當做config-client,模模擬實的環境

父專案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.pupeiyuan.springcloud</groupId> <artifactId>spring-Cloud</
artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <!-- 包含的子專案 --> <modules> <module>springcloud-eureka</module> <module>springcloud-configServer</module> <module>springcloud-configClient</
module> <module>springcloud-ssmServer</module> </modules> <!-- java版本資訊 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <!-- springboot以來的父專案 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencyManagement> <dependencies> <!-- springcloud版本依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.SR3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <!-- maven外掛 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

此專案pom.xml

<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>
    <parent>
        <groupId>com.pupeiyuan.springcloud</groupId>
        <artifactId>spring-Cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>springcloud-ssmServer</artifactId>

    <dependencies>
        <!-- 單元測試 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 支援springWEB web支援: 1、web mvc; 2、restful; 3、jackjson支援; 4、aop ........ -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- AOP依賴模組 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.7</version>
        </dependency>
        <!-- jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- 通用Mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!-- 分頁助手 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- mysql 資料庫驅動. -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 連線池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!-- JSP相關 -->
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>

        <!-- spring cloud -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- java編譯外掛 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- 這是spring boot devtool plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!--fork : 如果沒有該項配置,肯呢個devtools不會起作用,即應用不會restart -->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

建立 bootstrap.properties

config檔案中這裡要建立bootstrap.properties或者bootstrap.yml,一些關於config的配置需要在這裡配置,因為spring cloud預設從這個配置檔案中讀取config,其他的配置還可以從燕來的配置檔案application.properties中來設定

spring.application.name=multiple #這裡的名字對應的配置服務中的應用名稱{application}
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.service-id=pringcloud-configServer #這裡是config--server在eureka中註冊的服務
spring.cloud.config.profile=test #這裡名字對應環境的標識{profile}
spring.cloud.config.label=master

eureka.client.serviceUrl.defaultZone=http://root:[email protected]:8000/eureka
eureka.instance.prefer-ip-address=true

 

MyBatisConfig.java

此配置檔案是初始化datasource註冊bean的

package com.pupeiyuan.config;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.github.pagehelper.PageHelper;
import com.pupeiyuan.core.DataSourceKey;
import com.pupeiyuan.core.DynamicRoutingDataSource;

import tk.mybatis.spring.annotation.MapperScan;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

@Configuration
@MapperScan("com.pupeiyuan.mapper")
public class MyBatisConfig {
      @Bean
        //此處的"multiple.datasource.master"需要你在application.properties中配置,詳細資訊看下面貼出的application.properties檔案。
        @ConfigurationProperties(prefix = "multiple.datasource.master")
        public DataSource dbMaster() {
          DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
          //配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
            try {
                druidDataSource.setFilters("stat,wall,log4j");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        
            // 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
            druidDataSource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");
            //合併多個DruidDataSource的監控資料
            druidDataSource.setUseGlobalDataSourceStat(true);
            return druidDataSource;
        }

        @Bean
        @ConfigurationProperties(prefix = "multiple.datasource.slave")
        public DataSource dbSlave1() {
             DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
              //配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
                try {
                    druidDataSource.setFilters("stat,wall,log4j");
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            
                // 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
                druidDataSource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");
                //合併多個DruidDataSource的監控資料
                druidDataSource.setUseGlobalDataSourceStat(true);
                return druidDataSource;
        }
        /**
         * 核心動態資料來源
         *
         * @return 資料來源例項
         */
        @Bean
        public DataSource dynamicDataSource() {
            DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
            dataSource.setDefaultTargetDataSource(dbMaster());
            Map<Object, Object> dataSourceMap = new HashMap<>(4);
            dataSourceMap.put(DataSourceKey.DB_MASTER, dbMaster());
            dataSourceMap.put(DataSourceKey.DB_SLAVE1, dbSlave1());
            dataSource.setTargetDataSources(dataSourceMap);
            return dataSource;
        }
    
        @Bean
        public SqlSessionFactory sqlSessionFactory() throws Exception {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dynamicDataSource());
            //此處設定為了解決找不到mapper檔案的問題
            //sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
            return sqlSessionFactoryBean.getObject();
        }
        @Bean
        public SqlSessionTemplate sqlSessionTemplate() throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory());
        }
        /**
         * 事務管理
         *
         * @return 事務管理例項
         */
        @Bean
        public PlatformTransactionManager platformTransactionManager() {
            return new DataSourceTransactionManager(dynamicDataSource());
        }
    
}

 

2.下面我們在啟動了config-server的前提下,啟動此專案,看是否能獲取到資料來源資訊,併成功裝配到spring

 

這裡測試沒有問題,說明已經成功的從config-server中獲取到了配置資訊