1. 使用
-
1.1 父工程引入对应版本的依赖,注意springboot , cloud, cloud-alibaba对应版本
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
-
1.2 创建服务提供者
- 依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
- 配置注册中心的地址和namespace, 要将该服务注册到那个注册中心的哪个环境
spring:
application:
name: provider
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: e7a8ccc6-10df-46cd-88a0-cf54157e8ace // 该namespace为dev
- 开启服务注册功能
@EnableDiscoveryClient
@SpringBootApplication
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
- 创建api对外暴露接口
@RestController
@RequestMapping("echoController")
public class EchoController {
@Value("${server.port}")
private int port;
@GetMapping("/echo/{string}")
public String echo(@PathVariable("string") String string){
return "this is provider at port:" + port + ", you want me to echo : "+ string;
}
}
1.3 创建服务消费者(调用方)
同样要将其注册到注册中心,然后通过注册中心发现被调用方
-
restTemplate方式完成调用
spring:
application:
name: consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: e7a8ccc6-10df-46cd-88a0-cf54157e8ace // namespace, group与provider相对应,否则将注册到不同的组,那么无法发现服务实例
@EnableDiscoveryClient
@SpringBootApplication()
public class ComsumerApplication {......}
简单通过restTemplate调用, restTemplate通过@Ribbon添加负载均衡
@RestController()
@RequestMapping("/something")
@RefreshScope //@RefreshScope 实现配置自动更新
public class SaySomethingController {
@Value("${something:0}")
private Integer something;
@Autowired
private DataSource dataSource;
@Autowired
RestTemplate restTemplate;
@GetMapping("/echo/{str}")
public String echo(@PathVariable("str") String str){
return restTemplate.getForObject("http://provider/echoController/echo/"+str, String.class);
}
}
1.4 测试
启动服务,创建两个provider实例和一个consumer实例, 完成测试