第一步:添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-spring-context</artifactId>
<version>0.2.2-RC1</version>
</dependency>
第二步:添加config
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableNacosDiscovery(globalProperties = @NacosProperties(serverAddr = "{nacos的ip}:8848"))
public class NacosConfiguration {
}
第三步:注入测试,以controller为例
使用@NacosInjected注入NamingService对象
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.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping
@CrossOrigin
public class NameController {
@NacosInjected
NamingService namingService;
@GetMapping("name")
public List<Instance> getService() throws NacosException {
List<Instance> allInstances = namingService.getAllInstances("admin-dev");
allInstances.forEach(all->{
System.err.println(all.getIp()); //ip
System.err.println(all.getPort()); //端口
});
return allInstances;
}
}
第四步:接口测试
返回数据:
控制台打印数据:
成功!