新建工程
由于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依赖
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
启动类
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<Instance> service(@RequestParam String serviceName) throws NacosException {
return namingService.getAllInstances(serviceName);
}
}
以上配置完成后,启动服务,在浏览器中访问:
http://localhost:8089/discovery/service?serviceName=nacos-discovery