天天看點

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

每個功能為一個服務,可以獨立部署

METHOD PATH DESCRIPTION
GET /accounts/{account} Get specified account data
/accounts/current Get current account data
/accounts/demo Get demo account data (pre-filled incomes/expenses items, etc)
PUT Save current account data
POST /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機制!

請求走統一的入口,然後根據配置去反向代理,一般地會在目前入口後加一個二級路徑即可,在用戶端看來他就好像是一個系統!

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<DataPoint> getStatisticsByAccountName(@PathVariable String name) {
    return statisticsService.findByAccountName(name);
}      

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

 感謝各位的閱讀!

作者:倉儲大叔,張占嶺,

榮譽:微軟MVP

QQ:853066980

支付寶掃一掃,為大叔打賞!

springcloud~演化的微服務架構