spring-boot中使用nacos

一、啓動nacos服務

1、下載源碼或者安裝包
安裝包地址:https://github.com/alibaba/nacos/releases

2、解壓後進入nacos/bin目錄

3、輸入命令啓動服務,默認standalone,非集羣
linux:

sh startup.sh -m standalone


windows:

cmd startup.cmd

nacos默認使用8848端口,可通過http://127.0.0.1:8848/nacos/index.html進入自帶的控制檯界面,默認用戶名/密碼是nacos/nacos

Sample

 

二、配置管理

新建一個springboot的maven項目,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">
    <parent>
        <artifactId>spring-boot-nacos-test</artifactId>
        <groupId>spring.boot.nacos.test</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-boot-nacos-config-test</artifactId>
    <properties>
        <nacos-config-spring-boot.version>0.2.1</nacos-config-spring-boot.version>
    </properties>
    <dependencies>

        <!-- Spring Boot dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>${nacos-config-spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-actuator</artifactId>
            <version>${nacos-config-spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>2.11.2</version>
            <type>pom</type>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.6.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

在resource目錄下建application.properties,配置如下:

nacos.config.server-addr=127.0.0.1:8848
server.port=1001

新建入口類ConfigApplication:

package com.boot.nacos.sample;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;



@SpringBootApplication
@RestController
@NacosPropertySource(dataId = ConfigApplication.DATA_ID, autoRefreshed = true)
public class ConfigApplication {
    public static final String DATA_ID = "springboot2-nacos-config";

    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication.class,args);
    }
    @NacosValue(value = "${nacos.test.propertie:1111}",autoRefreshed = true)
    private String propertie;
    @RequestMapping(value = "/get",method = RequestMethod.GET)
    @ResponseBody
    public String get(){
        return propertie;
    }
}

在nacos配置管理-配置列表中新增配置,data_id和上面入口類中data_id一致,group默認DEFAULT_GROUP,配置內容爲

nacos.test.propertie=test

啓動入口類main方法,訪問地址:http://127.0.0.1:1001/get

出現配置管理中的信息,表示已經使用配置中心的配置了

三、服務發現

1、生產者

新建生產者服務spring-boot-nacos-provider-test,pom如下:

<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<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>
        <artifactId>spring-boot-nacos-test</artifactId>
        <groupId>spring.boot.nacos.test</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>spring-boot-nacos-provider</artifactId>
    <packaging>jar</packaging>
    <name>Nacos Spring Boot Discovery Provider Sample</name>
    <description>Nacos Spring Boot Discovery Provider Sample</description>
    <modules>

    </modules>
    <dependencies>

        <!-- Spring Boot dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-starter</artifactId>
            <version>0.2.7</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-actuator</artifactId>
            <version>0.2.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.0.3.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

新建測試controller類TestController

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

    @RequestMapping(value = "/{string}", method = RequestMethod.GET)
    @ResponseBody
    public String echo(@PathVariable String string) {
        return "Hello Nacos Discovery " + string;
    }
}

入口類ProviderApplication

@SpringBootApplication
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class,args);
    }
}

resource新建配置文件application.properties

nacos.discovery.server-addr=127.0.0.1:8848

server.port=1002
spring.application.name=nacos-provider
##服務自動註冊開啓
nacos.discovery.auto-register=true
nacos.discovery.register.ip=127.0.0.1
nacos.discovery.register.port=1002
nacos.discovery.register.weight=1.0D
nacos.discovery.register.healthy=false
nacos.discovery.register.enabled=true
nacos.discovery.register.ephemeral=true
nacos.discovery.register.clusterName=SPRINGBOOT
nacos.discovery.register.groupName=DEFAULT_GROUP
nacos.discovery.register.metadata.username=test

啓動入口類,訪問地址http://127.0.0.1:1002/test/2020,成功訪問

2、消費者

新建消費者服務spring-boot-nacos-consumer-test,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">
    <parent>
        <artifactId>spring-boot-nacos-test</artifactId>
        <groupId>spring.boot.nacos.test</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <name>Nacos Spring Boot Discovery Consumer Sample</name>
    <description>Nacos Spring Boot Discovery Consumer Sample</description>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-boot-nacos-consumer-test</artifactId>
    <dependencies>

        <!-- Spring Boot dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-starter</artifactId>
            <version>0.2.7</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-actuator</artifactId>
            <version>0.2.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.0.3.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

新建自動配置類RestTemplateConfig,爲了實例化RestTemplate

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

新建入口類ConsumerApplication

@SpringBootApplication
@RestController
public class ConsumerApplication {

    @Autowired
    private RestTemplate restTemplate;
    @NacosInjected
    private NamingService namingService;

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }
    @RequestMapping(value = "/test/{str}", method = RequestMethod.GET)
    public String get(@PathVariable String str){
        try {
            if (namingService != null) {
                Instance instance = namingService.selectOneHealthyInstance("nacos-provider");
                String url = "http://" + instance.getIp() + ":" + instance.getPort() + "/test/"+str;
                return restTemplate.getForObject(url, String.class);
            }
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }
}

resource下新建配置文件application.properties

nacos.discovery.server-addr=127.0.0.1:8848

server.port=1003
spring.application.name=nacos-consumer

先啓動生產者會發現nacos服務管理頁出現了生產者服務

然後啓動消費者服務,訪問http://127.0.0.1:1003/test,成功訪問並且調用到了生產者

源碼地址:https://gitee.com/ctslyw/spring-boot-nacos.git

 

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