Spring Cloud 微服务架构的五脏六腑!
Spring Cloud 是一个基于 Spring Boot 实现的微服务框架,它包含了实现微服务架构所需的各种组件。
注:Spring Boot 简单理解就是简化 Spring 项目的搭建、配置、组合的框架。因为与构建微服务本身没有直接关系,所以本文不对 Spring Boot 进行展开。
另外本文有一些例子涉及到 Spring 和 Spring Boot,建议先了解一下 Spring 和 Spring Boot 再阅读本文。
本文的阅读对象主要是没有接触过服务架构,想对其有一个宏观的了解的同学。
本文将从 Spring Cloud 出发,分两小节讲述微服务框架的「五脏六腑」:
- 第一小节「服务架构」旨在说明的包括两点,一服务架构是什么及其必要性;二是服务架构的基本组成。为什么第一节写服务架构而不是微服务架构呢?原因主要是微服务架构本身与服务架构有着千丝万缕的关系,服务架构是微服务架构的根基。 
- 第二小节「五脏六腑」则将结合 Spring Cloud 这个特例来介绍一个完整的微服务框架的组成。 
面向服务的架构和微服务架构
- 服务在哪?(服务治理问题) 
- 怎么调用?(服务调用问题) 
@EnableEurekaServer 表示该 Spring Boot 应用是一个注册中心。@SpringBootApplication
public class EurekaserverApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaserverApplication.class, args);
}
}
eureka.client.registerWithEureka: false 和fetchRegistry: false 来表明自己是一个 eureka server。
port: 8080
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
service-hello 服务
@EnableEurekaClient 表示他是一个 Eureka 客户端,它会在注册中心注册自己。@RestController 表示这是一个控制器,@RequestMapping("/hello") 表示匹配到请求 '/hello' 时会调用该方法进行响应。@EnableEurekaClient
@RestController
public class ServiceHelloApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHelloApplication.class, args);
}
@Value("${server.port}")
String port;
@RequestMapping("/hello")
public String home(@RequestParam String name) {
return "hello "+name+",i am from port:" +port;
}
}
http://localhost:8080/eureka/,也就是上面我们定义的。服务名为 service-hello,将会被调用者使用。client:
serviceUrl:
defaultZone: http://localhost:8080/eureka/
server:
port: 8081
spring:
application:
name: service-hello
服务消费者 service-ribbon
HelloControler 接收到请求,并调用 HelloService 中的 helloService 方法,HelloService 中通过定义的 restTemplate 去调用 http://service-hello/hello。此处要注意的是 @LoadBalanced 注解,它表示启用负载均衡。@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String helloService(String name) {
return restTemplate.getForObject("http://service-hello/hello?name="+name,String.class);
}
}
@RestController
public class HelloControler {
@Autowired
HelloService helloService;
@RequestMapping(value = "/hello")
public String hello(@RequestParam String name){
return helloService.helloService(name);
}
}
服务“雪崩”与断路器
服务暴露与路由网关
服务配置与配置中心
 Spring Cloud 提供了 Spring Cloud Config 组件,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程 Git 仓库中,帮助我们管理服务的配置信息。
Spring Cloud 提供了 Spring Cloud Config 组件,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程 Git 仓库中,帮助我们管理服务的配置信息。信息同步与消息总线
问题定位与链路追踪

怎么接私活?这个渠道你100%有用!请收藏! 
喜欢文章,点个在看 
评论


