spring-boot中使用nacos

2 篇文章 0 订阅

一、启动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

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值