SpringCloud簡明教程配置彙總筆記

本文涵蓋 spring cloud 學習示例程序,eureka,feign,rebbion,hystrix,zuul,config,bus使用示例(使用svn管理配置) 。css

Eureka註冊中心

Eureka服務端配置

@EnableEurekaServerhtml

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false #是否將eureka自身做爲應用註冊到eureka註冊中心
    fetch-registry: false #爲true時,能夠啓動,但報異常:Cannot execute request on any known server
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Eureka客戶端配置

@EnableDiscoveryClientjava

spring:
  application:
    name: service-a
eureka:
  client:
    serviceUrl:
          defaultZone: http://localhost:8010/eureka/ #eureka服務註冊地址

Ribbon 客戶端的負載均衡

在注入RestTemplate調用服務時,加註解@LoadBalanced便可實現客戶端的負載均衡。web

Feign 做爲http客戶端,調用服務

@EnableFeignClientsspring

@FeignClient(value = "service-provider")
public interface IProviderClient {

    @RequestMapping(method = RequestMethod.GET, value = "/car/{id}")
    String getCar(@PathVariable("id") int id);
}

創建一個接口,使用@FeignClient(value = "service-provider")註解標明要調用的服務名稱爲service-provider;在方法上使用@RequestMapping標明要調用的接口地址。以後在代碼中調用這個方法,就會使用Feign做爲http客戶端去調用對應的接口。服務器

Hystrix 熔斷器保護被調用的服務方法

@EnableCircuitBreakersession

feign:	
  hystrix:
    enabled: true
hystrix:
  command:
#    IProviderClient#getCar():      # 這是commandKey
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 2000   # 熔斷條件1:請求超時時間
      circuitBreaker:
        requestVolumeThreshold: 10        # 熔斷條件2:線程池的大小(每個hystrix的command都分配一個線程池執行,即某時刻只容許最多同時10個客戶端的請求)

若是調用失敗,在feign的接口客戶端添加fallback方法,便可設置默認的返回結果。以下:app

@FeignClient(value = "service-provider", fallback = IProviderClientImpl.class)
public interface IProviderClient {

    @RequestMapping(method = RequestMethod.GET, value = "/car/{id}")
    String getCar(@PathVariable("id") int id);
}

IProviderClientImpl中getCar方法的返回值即爲默認的返回值。負載均衡

Zuul 網關分發

@EnableZuulProxyjvm

zuul:
  ignored-services: microservice-provider-user # 須要忽視的服務(配置後將不會被路由)
  routes:
    first:
      path: /first/**     # 若路由名稱配置爲 first 則能夠省略這句 (訪問http://localhost/first/ca/23)
      url: http://localhost:8080    # 簡單路由
    second:
      path: /second/**
      url: forward:/second   # 轉發路由
    third:
      path: /third/**
      service-id: service-invoker

Config 配置中心

Config服務端

@EnableConfigServer

server:
  port: 8888
spring:
  application:
    name: config-server
  profiles:
    active: subversion
  cloud:
    config:
      server:
        svn:
          uri: https://192.168.50.33/svn/test
          username: yawn
          password: yawn
          default-label: trunk
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
management:
  security:
    enabled: false

Config 客戶端

spring:
  application:
    name: config-client
  cloud:
    config:
      discovery:
        enabled: true       # 根據服務id去查找配置服務器
        service-id: config-server   # 替代配置uri
      fail-fast: true
#      uri: http://localhost:8888
      profile: dev
      name: config-client
      label: trunk         # /trunk/config-client-dev.yml 也能夠不指定,由於服務端指定default-label
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
management:
  security:
    enabled: false

http請求讀取配置的匹配規則:

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

SpringCloud 單點登錄

基於 auth2.0 協議的認證

認證服務器

@EnableAuthorizationServer

server:
  port: 9999
  context-path: /uaa
security:
#  sessions: if_required
  ignored: /css/**,/js/**,/favicon.ico,/webjars/**
  user:
    name: yawn
    password: yawn
  oauth2:
    client:
      client-id: yawnClient
      client-secret: 123456
      scope: openid     # 表示權限範圍,可選項,用戶受權頁面時進行選擇
      authorized-grant-types: authorization_code #,refresh_token,password,client_credentials     # 有四種受權方式

資源服務器(用來向客戶端提供用戶的信息)

@EnableResourceServer

@Configuration
@EnableResourceServer
@RestController
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @GetMapping("user")
    public Map user(Principal principal) {
        Map user = new HashMap(4);
        user.put("name", principal.getName());
        user.put("description", principal.toString());
        return user;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // Resource Server 的配置, 客戶端獲取用戶信息 
        http.antMatcher("/user").authorizeRequests().anyRequest()
            .authenticated();
    }
}

須要認證的客戶端

@EnableOAuth2Sso

server:
  port: 8080
security:
  oauth2:
    client:
      client-id: yawnClient
      client-secret: 123456
      access-token-uri: http://localhost:9999/uaa/oauth/token
      user-authorization-uri: http://localhost:9999/uaa/oauth/authorize
    resource:
      user-info-uri: http://localhost:9999/uaa/user

以上是springcloud各個組件的基本配置和使用方法,記錄以備查詢。

原文發佈自 java技術分享站(jvm123.com):http://jvm123.com/2019/09/springcloud-jian.html

相關文章
相關標籤/搜索