一、概述
SpringCloud是一个基于SpringBoot开发的微服务框架,使用SpringCloud可以快速、简单、可靠地开发、部署和管理集群的微服务。
本文将从搭建过程、功能模块和代码实现三个方面介绍如何使用SpringCloud构建微服务应用。
二、搭建过程
1. 创建SpringBoot项目
# 依赖
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
}
2. 配置文件application.yaml
server:
port: 8080
spring:
application:
name: springcloud-demo
cloud:
# eureka注册中心配置
discovery:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka/
3. 创建服务提供者
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ProviderApplication {
@Value("${server.port}")
String port;
@RequestMapping("/hello")
public String home(@RequestParam String name) {
return "hello " + name + ",i am from port:" + port;
}
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
4. 创建服务消费者
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
@Autowired
RestTemplate restTemplate;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@RequestMapping("/hello")
public String hello(@RequestParam String name) {
return restTemplate.getForObject("http://springcloud-demo/hello?name=" + name, String.class);
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
5. 创建Eureka Server
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
三、功能模块
1. 服务注册与发现
使用Eureka Server作为注册中心,将服务提供者注册到其中,服务消费者通过发现注册中心中的服务实现负载均衡,从而实现服务间的调用。
2. 服务消费者负载均衡
RestTemplate是Spring提供的用于访问Rest服务的客户端,可以通过@LoadBalanced注解实现服务消费者的负载均衡。
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
3. 服务熔断
使用Hystrix实现服务熔断,当请求服务失败达到一定阈值时,自动开启熔断保护,防止雪崩效应。
在服务提供者的接口方法上添加@HystrixCommand注解,指定降级方法。
@RestController
public class ProviderController {
@RequestMapping("/hello")
@HystrixCommand(fallbackMethod = "helloFallback")
public String hello(@RequestParam String name) {
return "Hello, " + name + "!";
}
public String helloFallback(String name) {
return "Fallback: Hello, " + name + "!";
}
}
4. 微服务链路追踪
使用SpringCloud的Zipkin和Sleuth实现微服务链路追踪,可以查看每个服务的请求响应时间,以及服务间调用的关系。
四、代码实现
完整的代码示例可以查看我的Github仓库https://github.com/xinliangnote/SpringCloud
原创文章,作者:NIRWC,如若转载,请注明出处:https://www.506064.com/n/361027.html
微信扫一扫
支付宝扫一扫