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

1. 前言

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

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

2. 创建消费者项目

Nacos基础教程(四)--------Nacos+SpringBoot服务发现_第1张图片

3. 引入相关包


<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.0modelVersion>
    <parent>
        <groupId>cn.yzstugroupId>
        <artifactId>learn-springbootartifactId>
        <version>1.0version>
        <relativePath/> 
    parent>
    <groupId>cn.yzstugroupId>
    <artifactId>learn-nacos-consumerartifactId>
    <version>1.0version>
    <name>learn-nacos-consumername>
    <description>nacos消费者description>

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

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

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <version>${springboot.version}version>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>

        
        
        <dependency>
            <groupId>com.alibaba.bootgroupId>
            <artifactId>nacos-config-spring-boot-starterartifactId>
            <version>${nacos.config.version}version>
        dependency>
        <dependency>
            <groupId>com.alibaba.bootgroupId>
            <artifactId>nacos-discovery-spring-boot-starterartifactId>
            <version>${nacos.discovery.version}version>
        dependency>
        
        
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>${swagger2.version}version>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>${swagger2.version}version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
            <version>${springboot.version}version>
            <scope>compilescope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <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. 服务发现检测

启动消费者服务和上篇文章的服务
Nacos基础教程(四)--------Nacos+SpringBoot服务发现_第2张图片

发现服务成功

8. 总结

发现服务过程中,需要做的是导discovery包,配置服务中心地址,提供发现服务的接口/方法。这个项目中有许多配置是为了以后的工作顺利而做的,大家注意区分。
如果在学习过程出现问题,欢迎关注我的公众号,与我在线交流
Nacos基础教程(四)--------Nacos+SpringBoot服务发现_第3张图片

项目地址: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服务器

更多文章请点击

你可能感兴趣的:(SpringBoot,nocas)