SpringBoot使用Nacos做配置中心以及服務註冊發現(SpringCloud版本)以及Feign集成調用

上節講的Nacos做SpringBoot項目的配置中心以及服務發現,並不好用。不能自動服務註冊以及配置非常難用(也可能是我沒找到便捷的方法),然後就將SpringCloud版本的集成操作一下(爲後面學習消息隊列RabbitMQ(也可能是RocketMQ)以及Seata做鋪墊)。集成了一天,小細節很難發現,我等菜雞一定要注意約定的力量。

下面基於Nacos服務已經啓動的基礎上,所以下載Nacos點擊這裏,zip是windows的tar.gz是linux的,也可以下載源碼自行構建。

官方文檔https://github.com/alibaba/spring-cloud-alibaba/wiki/Nacos-config

首先上一下項目構成

然後POM版本依賴,這裏也困擾好久,一直都註冊不上去後來查看很多文檔才知道要加入Cloud的依賴,官方文檔又沒講。

這個項目所有公共依賴都在主POM中所以子模塊中是沒有依賴的。

1.要注意的是dependencyManagement中的依賴

2.SpringBoot版本還是不要大於2.2,nacos-config依賴是Nacos做配置中心要使用的依賴,nacos-discovery依賴是Nacos做服務註冊發現要使用的依賴

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.xiaohe</groupId>
    <artifactId>seata-mq</artifactId>
    <version>10.01.01</version>
    <name>seata-mq</name>
    <packaging>pom</packaging>

    <properties>
        <test.project.version>10.01.01</test.project.version>
        <java.version>1.8</java.version>
        <nacos.config.vsersion>0.2.1.RELEASE</nacos.config.vsersion>
        <fastjson.version>1.1.28</fastjson.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
        <spring-cloud-alibaba.version>0.2.1.RELEASE</spring-cloud-alibaba.version>
    </properties>
    <modules>
        <module>seata-mq-one</module>
        <module>seata-mq-two</module>
    </modules>

    <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>
            <!--SpringCloud Alibaba-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

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

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

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

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- nacos配置依賴引入的是springcloud的nacos依賴所以上面要加入springcloud的依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>${nacos.config.vsersion}</version>
        </dependency>
        <!-- 服務發現依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${nacos.config.vsersion}</version>
        </dependency>
        <!-- feign遠程調用依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

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

</project>

整合Nacos要有關於Nacos配置的配置文件bootstrap.properties,要注意使用默認的命名空間就別寫namespace=public了,這個搞得我崩潰。文件後綴也是要注意的是Nacos裏面要將dataID打全!我這裏是seata-mq-dev.yaml

#指定開發環境
spring.profiles.active=dev
#服務器地址
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
#如果要用默認Public命名空間,就他媽別寫,要不然他媽的一直讀不到
#spring.cloud.nacos.config.namespace=ffcbccbd-667a-4b2e-bc05-695e598af54a
#指定配置羣組 --如果是DEFAULT_GROUP組 則可以省略羣組配置
spring.cloud.nacos.config.group=DEFAULT_GROUP
#文件名 -- 如果沒有配置則默認爲 ${spring.appliction.name}
spring.cloud.nacos.config.prefix=seata-mq
#指定文件後綴
spring.cloud.nacos.config.file-extension=yaml

要開啓服務註冊與發現加入discovery依賴之後在application.yml中加入服務發現地址

server:
  port: 8080

spring:
  application:
    name: seata-mq-one
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
#爲了測試服務增加了Feign,默認熔斷關閉這個配置開啓熔斷
feign:
  hystrix:
    enabled: true

以上配置不要落下,下面開始貼Application啓動類,喜歡將解釋放入代碼註釋中,能複製堅決不多打一個字!!!O(∩_∩)O哈哈~

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;


@Slf4j
//這裏要將默認數據源關閉,因爲暫時沒有配置。
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
//啓用服務發現註解
@EnableDiscoveryClient
//Feign開啓註解,basePackages和value功能相同,隨意一個都可以。裏面是feign掃描包路徑
@EnableFeignClients(basePackages = {"com.xiaohe"},value = {"com.xiaohe"})
public class SeataMqTwoApplication {

    public static void main(String[] args) {
        log.info("seata-mq-two準備啓動");
        SpringApplication.run(SeataMqTwoApplication.class, args);
    }

}

然後成果

服務註冊發現

配置中心

爲了檢測是否讀取了配置以及feign的調用是否可用,寫了一個控制類進行檢測代碼如下

import com.xiaohe.seatamqtwo.feign.TwoClient;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

    //調用的two的feign接口client
    @Autowired
    private TwoClient twoClient;
    //這裏直接用value就可以了,同樣的:後面是默認值
    @Value("${test.msg:aYouMeiNaDao}")
    private String username;

    @GetMapping("/getMsg")
    public String getMsg(){
        System.out.println("msg內容是: "+username);
        return username;
    }
    //這裏遠程調用two服務的對外提供接口
    @GetMapping("/twoSayHello")
    public String twoSayHello(@RequestParam String name){
        return twoClient.twoSayHello(name);
    }
}

運行情況

順帶貼一下Feign的代碼,作以記錄(這裏偷懶將接口以及實現放到了一個微服務中,實際項目中應該抽象與實現分離開來,調用方只依賴服務提供方API模塊。面向接口編程)

1、定義一個遠程調用接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(
        value="seata-mq-two",
        fallback = TwoClientFallback.class
)
public interface TwoClient {

    @GetMapping("/twoSayHello")
    String twoSayHello(@RequestParam String name);
}

2、定義實現類

import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
public class TwoClientImpl implements TwoClient{


    @Override
    public String twoSayHello(String name) {
        return "hello,"+name+"! this is two client. ";
    }
}

3、定義熔斷

import org.springframework.stereotype.Component;

@Component
public class TwoClientFallback implements TwoClient{

    @Override
    public String twoSayHello(String name) {
        return "connection fail";
    }
}

倉庫地址:https://github.com/johnxiaohe/SpringCloud-Seata-Mq

有疑問或者修正的地方請留言,謝謝。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章