下面是一个使用 Spring Boot、Nacos、Feign 和 Spring Cloud 的简单服务调用示例。这个示例展示了如何设置一个微服务架构,其中一个服务调用另一个服务。
1. 服务间架构
我们将创建两个服务:
Service A:提供一个简单的接口。
Service B:通过 Feign 调用 Service A 的接口。
2. 创建 Nacos 服务注册中心
下载 Nacos:
从 Nacos GitHub 下载 Nacos。
启动 Nacos:
解压缩后,在解压目录中,运行:
./bin/startup.sh -m standalone # Linux/Mac
或者
startup.cmd -m standalone # Windows
3. 创建 Service A
3.1. 创建 Spring Boot 项目
使用 Spring Initializr 创建一个新的 Spring Boot 项目,选择以下依赖:
Spring Web
Spring Cloud Starter Netflix Eureka
Spring Cloud Starter OpenFeign
Spring Boot DevTools
Spring Boot Actuator
3.2. 修改 application.yml
server:
port: 8081
spring:
application:
name: service-a
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
3.3. 创建 Controller
package com.example.servicea.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Service A";
}
}
4. 创建 Service B
4.1. 创建 Spring Boot 项目
使用 Spring Initializr 创建另一个 Spring Boot 项目,选择以下依赖:
Spring Web
Spring Cloud Starter Netflix Eureka
Spring Cloud Starter OpenFeign
Spring Boot DevTools
Spring Boot Actuator
4.2. 修改 application.yml
server:
port: 8082
spring:
application:
name: service-b
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
4.3. 创建 Feign 客户端
package com.example.serviceb.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "service-a") // 服务名与 Service A 的 application.name 一致
public interface ServiceAClient {
@GetMapping("/hello")
String hello();
}
4.4. 创建 Controller
package com.example.serviceb.controller;
import com.example.serviceb.client.ServiceAClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private ServiceAClient serviceAClient;
@GetMapping("/call")
public String callServiceA() {
return serviceAClient.hello(); // 调用 Service A
}
}
5. 设置 Spring Cloud 和 Nacos 的依赖
确保在两个服务的 pom.xml 中添加 Spring Cloud 和 Nacos 的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
6. 启动服务
启动 Nacos。
启动 Service A(端口 8081)。
启动 Service B(端口 8082)。
7. 测试服务调用
打开浏览器或 Postman,访问 http://localhost:8082/call。
您应该看到从 Service A 返回的消息:
Hello from Service A