1. 程式人生 > >SpringBoot SpringCloud運用Euraka微服務架構(聚合分散式架構)Euraka釋出與消費

SpringBoot SpringCloud運用Euraka微服務架構(聚合分散式架構)Euraka釋出與消費

SpringBoot SpringCloud運用Euraka微服務架構

  • 首先說到SpringBooot專案架構,首選jdk1.8以上,當然啊,jdk1.7也不是不可以;
  • 我們本次要做的是建立父工程(pom),和多個子工程(pojo,common,server,web等),一箇中間件Euraka,程式設計工具IDEA;

  • 首先說父工程,只是做以來管理,和子模組管理,編碼統一所以說,不做單獨啟動;
  • pom檔案
<?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.公司名</groupId>
    <artifactId>公司名</artifactId>
    <packaging>pom</packaging>
    <version>0.0.1-SNAPSHOT</version>

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

    <!--制定 jdk 和 編碼-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.M1</spring-cloud.version>
    </properties>

    <!--模型管理-->
    <modules>
        <module>公司名_eureka</module>
        <module>公司名_pojo</module>
        <module>公司名_common</module>
        <module>公司名_core_server</module>
        <module>公司名_core_web</module>
    </modules>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <!--<scope>test</scope>-->
        </dependency>

        <!-- json-lib -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

        <!-- 整合 Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- jwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.6.0</version>
        </dependency>

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

        <!--junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

    </dependencies>

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

    <!--ScriptCloud-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>
  • 這樣就可以了建立的時候工程選項(jar,war,pom),可以選pom一定選pom,如果不能,選擇jar到pom檔案裡更改pom

 

  • 其他子模組,比如pojo和common,只做實體類,或者工具類使用,使用前install,jar放入本地倉庫
  • 這裡就不詳細說明了

 

  • Euraka 註冊中心,負責各模組呼叫與連結,這裡只做中介軟體使用
  • 建立jar工程 , pom檔案配置
<?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.公司名</groupId>
    <artifactId>公司名_eureka</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>公司名_eureka</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.hn</groupId>
        <artifactId>hn</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <!--Eureka server 依賴-->
    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <!--Eureka lock-->
        <!--<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

 

  • properties配置
#埠號
server.port = 7517
#服務名
spring.application.name = Eureka

#Eurekalock 
#security.basic.enabled = true
#security.user.name = user
#security.user.password = 123456

#EurekaServer
eureka.instance.hostname = eureka

#Euraka 不註冊本身
eureka.client.register-with-eureka = false
eureka.client.fetch-registry = false

#建立註冊中心地址,專案中所有應用到Euraka都要註冊到這個地址
eureka.client.serviceUrl.defaultZone = http://localhost:7517/eureka/

 

  • 啟動類,注意這裡加入了@EnableEurekaServer ,表示自己是EurakaServer
package 公司名.eureka.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class 公司名EurekaApplication {

    public static void main(String[] args) {
        SpringApplication.run(公司名EurekaApplication.class, args);
    }
}
  • 這時候啟Euraka啟動類,訪問註冊中心地址就會看到Euraka介面了
  • 例如圖上:訪問 http:// ip + 埠

  • 建立接server工程,釋出訊息到Euraka,建立時宣告是jar工程
  • pom檔案引入
<?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.公司名</groupId>
    <artifactId>公司名_core_server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hn_core_server</name>
    <packaging>jar</packaging>

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

    <!--繼承-->
    <parent>
        <groupId>com.公司名</groupId>
        <artifactId>公司名</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <!--server 依賴-->
    <dependencies>

        <!-- 資料庫連線池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.26</version>
        </dependency>

        <!-- mysql odbc -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--ibatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!--eureka-server-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

    </dependencies>

    <build>        
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.公司名</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!-- 打包時跳過測試項 -->
                    <skip>true</skip>
                    <!-- jdk版本 -->
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            
            <!-- 釋出到tomcat下跳過測試項 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

  • properties配置
#CoreServer 埠號
server.port=8087

#服務名
spring.application.name=core_server

#資料庫連線配置
spring.datasource.name = 公司資料庫代稱
spring.datasource.url = jdbc:mysql://ip:埠/資料庫名
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.max-active = 20
spring.datasource.initial-size = 2
spring.datasource.max-idle=8
spring.datasource.min-idle=8

#\u4F7F\u7528druid\u6570\u636E\u6E90\u5F00\u542F
#spring.datasource.type = com.zaxxer.hikari.util.DriverDataSource

#\u8FDE\u63A5\u6C60\u914D\u7F6E
spring.datasource.dbcp2.max-wait-millis = 60000 
spring.datasource.dbcp2.min-idle = 1
spring.datasource.dbcp2.time-between-eviction-runs-millis = 60000
spring.datasource.dbcp2.min-evictable-idle-time-millis = 300000
spring.datasource.dbcp2.validation-query = select 'x'
spring.datasource.dbcp2.test-while-idle = true
spring.datasource.dbcp2.test-on-borrow = false
spring.datasource.dbcp2.test-on-return = false 
spring.datasource.dbcp2.pool-prepared-statements = true 
spring.datasource.dbcp2.max-open-prepared-statements = 20

#ibatis mapper.xml 指定ibatis。xml位置,這裡放在resources,mapping資料夾下了
mybatis.mapperLocations = classpath:mapping/*.xml
#ibatis model
#mybatis.type-aliases-package = com.hn.hn_core_server.model

#EurekaURL
eureka.client.serviceUrl.defaultZone = http://localhost:7517/eureka/

 

  • 啟動類 ,這裡加入了@EnableDiscoveryClient , 生命自己是Euraka客戶端
package com.公司名.公司名_core_server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableDiscoveryClient
@SpringBootApplication
public class 公司名CoreServerApplication extends SpringBootServletInitializer {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(HnCoreServerApplication.class, args);
    }
}

 

  • Controller 釋出訊息
package com.公司名.公司名_core_server.controller;

import com.公司名.公司名_core_server.service.TestService;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class TestController {


    @Autowired
    private EurekaClient eurekaClient;

    /**
     * Eureka Test
     */
    @GetMapping("/testGetList")
    public String testGetList (){

        System.out.println("-----------------------Eureka 呼叫了我!------------------------------");
        
        return "Hello ,Eureka";
    }

    @GetMapping("/eureka-instance")
    public String serviceUrl() {
        InstanceInfo instance = this.eurekaClient.getNextServerFromEureka("PROVIDER-USER-DEMO2", false);
        return instance.getHomePageUrl();
    }

}
  • 這時候,我們啟動該工程啟動類,就會將訊息釋出到註冊中心,訪問註冊中心,也會註冊到註冊中心,顯示的是我們的服務名

  • 建立web工程,實現與介面對接,建立時宣告是war工程
  • pom檔案引入依賴
<?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.公司名</groupId>
    <artifactId>公司名_core_web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>公司名_core_web</name>

    <parent>
        <groupId>com.公司名</groupId>
        <artifactId>公司名</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <!--web 依賴-->
    <dependencies>

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

        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>         
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!-- 打包時跳過測試項 -->
                    <skip>true</skip>
                    <!-- jdk版本 -->
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            
            <!-- 釋出到tomcat下跳過測試項 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
  • properties 配置 這裡加入了thymeleaf靜態技術,需要把html放在resources目錄下
#Web埠號
server.port=8088

#服務名
spring.application.name=core_web

#thymelea模板配置 html放在resources下webapp資料夾下
spring.thymeleaf.prefix=classpath:/webapp/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8

#熱部署檔案,頁面不產生快取,及時更新
spring.thymeleaf.cache = false
spring.resources.chain.strategy.content.enabled = true
spring.resources.chain.strategy.content.paths = /**


#客戶端註冊中心地址
eureka.client.serviceUrl.defaultZone= http://localhost:7517/eureka/
  • 啟動類 這裡也加入了@EnableDiscoveryClient,宣告自己是Eureka客戶端,建立RestTemplate準備呼叫資訊
package com.公司名.公司名_core_web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@SpringBootApplication
public class 公司名CoreWebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(HnCoreWebApplication.class, args);

    }

    @Bean
    RestTemplate restTemplate(){ return new RestTemplate(); }
}
  • 服務呼叫 
  • 注入RestTemplate物件,RestTemplate物件用法很多,這裡只說框架,RestTemplate用法就不詳解了
  • url:這裡的URL是釋出訊息的Euraka客戶端,也就是該專案的Server工程,ip + mapping 對映地址
package com.公司名.公司名_core_web.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
public class TestController {


    @Autowired
    private RestTemplate restTemplate;
    

    @GetMapping("/test")
    public String testGetList2 (Class responseType){

        ResponseEntity<String> forEntity = this.restTemplate.getForEntity("http://localhost:8087/test/testGetList", String.class);
        return forEntity.getBody();
    }
}
  • 現在啟動該服務,在註冊中心觀察,也會註冊到註冊中心,顯示服務名

  • 訪問該工程地址 , 而不是註冊中心地址,訪問請求方法,就會看到呼叫得到的資訊,該工程地址:
  • localhost:8088/test
  • 頁面會顯示我們儲存的資訊
  • CoreServer控制檯資訊

 

  • 最後要呼叫公共類,比如專案中的common、pojo 需要引入他們做自己的依賴

chenyb 隨筆記錄,只為方便自己學習

2018-11-05