springcloud~演化的微服务架构

微服务

将整体功能按着模块划分成多个独立的单元,这些单元可以独立部署,它们之前通过轻量级的web api方式进行通讯,对于微服务框架来说,最流行的就是springcloud和Service Fabric,前者是java开发,后者是.net的产品,今天主要介绍一下springcloud!

参考文章: https://dzone.com/articles/microservice-architecture-with-spring-cloud-and-do

  1. 功能即服务
  2. 配置中心
  3. 服务注册和发现
  4. 熔断器和监视器
  5. 解耦和异步通和的消息队列
  6. Api网关
  7. 统一授权服务
  8. Feign代替传统的Http

功能即服务-Functional Services

每个功能为一个服务,可以独立部署

METHODPATHDESCRIPTIONGET/accounts/{account}Get specified account dataGET/accounts/currentGet current account dataGET/accounts/demoGet demo account data (pre-filled incomes/expenses items, etc)PUT/accounts/currentSave current account dataPOST/accounts/Register new account

配置中心-Config Server

所有项目的配置信息都存储在远程,启动后同步到本地,有过期机制

spring:

application:

name: notification-service

cloud:

config:

uri: http://config:8888

fail-fast: true

服务注册和发现-Eureka

每个服务在启动后都被注册到eureka里,其它服务从eureka里通过服务名拿到服务的地址,进行调用

spring:

application:

name: notification-service

熔断器和监视器- Hystrix Dashboard

当服务进行相互调用后,它可能是多层次的调用,当某一层出现问题后,它下面的服务就不需要等待超时了,直接返回失败,这就是熔断器;而每个服务运行的状态可以使用监视器查看到。

@SpringBootApplication

@EnableDiscoveryClient

@EnableFeignClients

@EnableHystrixDashboard

@EnableCircuitBreaker

public class ConsumerApplication {

public static void main(String[] args) {

SpringApplication.run(ConsumerApplication.class, args);

}

}

解耦和异步通和的消息队列

队列服务用了比较流行的rabbitmq,比起kafka来说,它不仅更轻,而且更安全,有自己的ack机制!

Api网关

请求走统一的入口,然后根据配置去反向代理,一般地会在当前入口后加一个二级路径即可,在客户端看来他就好像是一个系统!

zuul:

routes:

notification-service:

path: /notifications/**

serviceId: notification-service

stripPrefix: false

所有接口都可以被授权注解统一拦截,进行授权,一般采用oauth2的协议!

@PreAuthorize("#oauth2.hasScope('server')")

@RequestMapping(value = "accounts/{name}", method = RequestMethod.GET)

public List getStatisticsByAccountName(@PathVariable String name) {

return statisticsService.findByAccountName(name);

}

Feign代替传统的Http

Feign是通过定义本地接口来模拟对远程接口的调用的,在生产环境中它会使用服务名+Feign接口路径来实现对远程资源的调用,而在测试环境里,他又会根据你mock的接口进行调用,这对于TDD开发是非常必要的,你在测试时不需要依赖外部资源!

@FeignClient(name = "statistics-service")

public interface StatisticsServiceClient {

@RequestMapping(method = RequestMethod.PUT, value = "/statistics/{accountName}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)

void updateStatistics(@PathVariable("accountName") String accountName, Account account);

}

几大服务组件的默认端口对应表

  • localhost:80 - Gateway
  • localhost:8761 - Eureka Dashboard
  • localhost:9000 - Hystrix Dashboard
  • localhost:8989 - Turbine stream (source for Hystrix Dashboard)
  • localhost:15672 - RabbitMq management

感谢各位的阅读!


分享到:


相關文章: