上一篇 Nacos 项目启动完成后。这里开始springcloud项目注册
不需要父工程,最简单的pom文件如下。
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>name.songjian</groupId>
<artifactId>nacos-consumer-simplest</artifactId>
<packaging>jar</packaging>
<version>0.1</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.4.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.2.2.RELEASE</version>
</dependency>
</dependencies>
</project>
生产者消费者的yml文件一样。只需要改一下端口号和项目名称
server:
#项目端口
port: 8001
spring:
application:
#项目名称
name: nacos-provider-simplest
cloud:
nacos:
discovery:
#Nacos服务器IP地址 和端口号
server-addr: 127.0.0.1:8848
生产者代码,启动就可以访问了。例如:localhost:8001/echo/test
@SpringBootApplication
@EnableDiscoveryClient
public class FrameworkApplication {
@RestController
static class EchoController {
@GetMapping("/echo/{string}")
public String echo(@PathVariable String string) {
return "nacos-provider 8001 " + string;
}
}
public static void main(String[] args) {
SpringApplication.run(FrameworkApplication.class, args);
}
}
消费者代码,调用生产者代码。访问:localhost:8002/echo/test。
@SpringBootApplication
@EnableDiscoveryClient
public class FrameworkApplication {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@RestController
static class TestController {
private final RestTemplate restTemplate;
public TestController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@RequestMapping(value="/echo/{str}", method=RequestMethod.GET)
public String echo(@PathVariable String str) {
return restTemplate.getForObject("http://nacos-provider-simplest/echo/" + str, String.class);
}
}
public static void main(String[] args) {
SpringApplication.run(FrameworkApplication.class, args);
}
}