SpringCloud简明教程笔记

  • 2019 年 10 月 6 日
  • 筆記

本文涵盖 spring cloud 学习示例程序,eureka,feign,rebbion,hystrix,zuul,config,bus使用示例(使用svn管理配置) 。

Eureka注册中心

Eureka服务端配置

@EnableEurekaServer

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客户端配置

@EnableDiscoveryClient

spring:    application:      name: service-a  eureka:    client:      serviceUrl:            defaultZone: http://localhost:8010/eureka/ #eureka服务注册地址

Ribbon 客户端的负载均衡

在注入RestTemplate调用服务时,加注解@LoadBalanced即可实现客户端的负载均衡。

Feign 作为http客户端,调用服务

@EnableFeignClients

@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 熔断器保护被调用的服务方法

@EnableCircuitBreaker

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方法,即可设置默认的返回结果。如下:

@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 网关分发

@EnableZuulProxy

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