Spring Boot是一种快速构建应用程序的框架,而Spring Cloud是一组用于构建分布式系统的工具集。它们可以方便地进行整合,下面给出一个简单的示例:
- 创建一个Spring Boot项目,添加以下依赖:
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Eureka Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!-- Eureka Discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 在application.yml中配置Eureka Server:
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
- 创建一个简单的服务提供者,添加以下依赖:
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Eureka Discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 在application.yml中配置服务提供者:
server:
port: 8080
spring:
application:
name: example-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
- 创建一个简单的服务消费者,添加以下依赖:
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Eureka Discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 在application.yml中配置服务消费者:
server:
port: 8081
spring:
application:
name: example-client
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
- 创建服务提供者的接口:
@RestController
@RequestMapping("/api")
public class ExampleController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
- 在服务消费者中调用服务提供者:
@RestController
public class ExampleController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/hello")
public String hello() {
String url = "http://example-service/api/hello";
return restTemplate.getForObject(url, String.class);
}
}
- 启动Eureka Server、服务提供者和服务消费者,访问http://localhost:8081/hello,即可看到"Hello, World!"的输出。
这是一个简单的示例,实际上Spring Cloud还有很多组件,比如Config、Gateway、Feign等,可以根据具体的需求进行整合。