nacos服务发现的最简单配置

新建工程

image.png
image.png

由于nacos不兼容spring boot 2.4.4版本,spring.io暂时无法在向导里面添加alibaba的maven依赖。

配置文件application.yaml

nacos:
  discovery:
    server-addr: 192.168.31.20:8848
spring:
  application:
    name: nacos-discovery

server:
  port: 8089

maven依赖


    com.alibaba.boot
    nacos-discovery-spring-boot-starter
    0.2.2


    org.springframework.boot
    spring-boot-starter-web
    RELEASE
    compile

启动类

package com.example.nacos.discovery;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class NacosDiscoveryDemoApplication {

    @NacosInjected
    private NamingService namingService;

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

    @Value("${server.port}")
    private Integer serverPort;

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

    @PostConstruct
    public void registerService() throws NacosException {
        namingService.registerInstance(applicationName,"192.168.31.20",serverPort);
    }

}

controller

package com.example.nacos.discovery.controller;

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.api.naming.pojo.Instance;
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("discovery")
public class DiscoveryController {

    @NacosInjected
    private NamingService namingService;

    @GetMapping("service")
    public List service(@RequestParam String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }
}

以上配置完成后,启动服务,在浏览器中访问:

http://localhost:8089/discovery/service?serviceName=nacos-discovery

image.png

你可能感兴趣的:(nacos服务发现的最简单配置)