Nacos基础教程(四)--------Nacos+SpringBoot服务发现

1. 前言

系列文章地址:https://blog.csdn.net/shouchenchuan5253/category_10223260.html

项目地址:https://gitee.com/dikeywork/learn-springboot

2. 创建消费者项目

在这里插入图片描述

3. 引入相关包

<?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>cn.yzstu</groupId>
        <artifactId>learn-springboot</artifactId>
        <version>1.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.yzstu</groupId>
    <artifactId>learn-nacos-consumer</artifactId>
    <version>1.0</version>
    <name>learn-nacos-consumer</name>
    <description>nacos消费者</description>

    <properties>
        <java.version>${java.version}</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${springboot.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 服务发现核心包:开始 -->
        <!-- 在服务发现中,配置中心服务并不是必须的 -->
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>${nacos.config.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-starter</artifactId>
            <version>${nacos.discovery.version}</version>
        </dependency>
        <!-- 服务发现核心包:结束 -->
        
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${springboot.version}</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${springboot.version}</version>
            </plugin>
        </plugins>
    </build>

</project>

这是pom完整文件,核心包在其中已经备注了。

4. 配置服务地址

server:
  port: 8089
  ip: 127.0.0.1

spring:
  application:
    name: nacos-consumer
nacos:
  config:
    server-addr: 127.0.0.1:8848 # 配置 Nacos 配置 的地址
  discovery:
    server-addr: 127.0.0.1:8848

5. 开启自动注册

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


/**
 * nacos配置类
 * @author baldwin
 */
@Configuration
@NacosPropertySource(dataId = "TestConfig.yml",groupId = "yzstu", autoRefreshed = true) //加载 dataId 为 example 的配置源,并开启自动更新
public class NacosConfig {
    @Value("${server.port}")
    private int serverPort;

    @Value("${server.ip}")
    private String ip;

    @Value("${spring.application.name}")
    private String applicationName;

    @NacosInjected
    private NamingService namingService;

    /**
     * 开机自动注册服务
     * @throws NacosException
     */
    @PostConstruct
    public void registerInstance() throws NacosException {
        namingService.registerInstance(applicationName, ip, serverPort);
    }
}

6. 相关接口

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
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;

import java.util.List;

@RestController
@RequestMapping(("/api/nacos"))
@Api(value = "Nacos服务相关接口")
@Data
public class NacosApi {

    @NacosInjected
    private NamingService namingService;

    @NacosValue(value = "${site.ip:0.0.0.0}",autoRefreshed = true)
    private String siteIp;

    @NacosValue(value = "${site.name:null}",autoRefreshed = true)
    private String siteName;

    @ApiOperation(value = "获取网站信息")
    @GetMapping(value = "/getSiteInfo")
    public String getSiteInfo(){
        return "MySite:"+siteName + ",ip:"+siteIp;
    }
    @ApiOperation(value = "获取实例信息")
    @ApiImplicitParam(value = "serviceName",example = "nacos-service",required = true)
    @GetMapping(value = "/getServiceInfo")
    public List<Instance> getInstanceInfo(@RequestParam(value = "serviceName") String serviceName){
        try {
            return namingService.getAllInstances(serviceName) ;
        } catch (Exception e){
            e.printStackTrace();
        }
        return null ;
    }
}

7. 服务发现检测

启动消费者服务和上篇文章的服务
在这里插入图片描述

发现服务成功

8. 总结

发现服务过程中,需要做的是导discovery包,配置服务中心地址,提供发现服务的接口/方法。这个项目中有许多配置是为了以后的工作顺利而做的,大家注意区分。
如果在学习过程出现问题,欢迎关注我的公众号,与我在线交流
在这里插入图片描述

项目地址:https://gitee.com/dikeywork/learn-springboot/tree/master/learn-nacos

系列文章地址:https://blog.csdn.net/shouchenchuan5253/category_10223260.html

我是Baldwin,一个25岁的程序员,致力于让学习变得更有趣,如果你也真正喜爱编程,真诚的希望与你交个朋友,一起在编程的海洋里徜徉!

往期好文:

用Python每天给女神发一句手机短信情话

MySQL优化之explain

Spring源码分析-MVC初始化

春风得意马蹄疾,一文看尽(JVM)虚拟机

造轮子的艺术

源码阅读技巧

Java注解详解

教你自建SpringBoot服务器

更多文章请点击

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值