springcloud项目实例
时间: 2023-10-19 18:09:36 浏览: 48
Spring Cloud 是一个基于 Spring Boot 实现的云应用开发工具,它为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理、服务发现、断路器、智能路由、微代理、控制总线等)。下面是一个简单的 Spring Cloud 项目实例:
1. 创建一个 Spring Boot 项目,添加以下依赖:
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
```
2. 在 `application.properties` 文件中添加以下配置:
```
spring.application.name=my-service
server.port=8080
# 配置中心相关配置
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.profile=dev
# Eureka 相关配置
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
```
3. 创建一个 RESTful API 接口:
```
@RestController
public class MyController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/hello")
public String hello() {
String result = restTemplate.getForObject("http://my-service2/hello", String.class);
return "Hello, " + result;
}
}
```
4. 创建一个服务注册中心:
```
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
```
5. 创建一个服务提供者:
```
@SpringBootApplication
@EnableDiscoveryClient
public class MyServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MyServiceApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
```
6. 创建另一个服务提供者:
```
@SpringBootApplication
@EnableDiscoveryClient
public class MyService2Application {
public static void main(String[] args) {
SpringApplication.run(MyService2Application.class, args);
}
@GetMapping("/hello")
public String hello() {
return "World";
}
}
```
7. 启动服务注册中心、服务提供者和服务消费者,访问 `http://localhost:8080/hello` 即可看到结果。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)