Summary Notes on Spring Cloud Concise Tutorial Configuration

Posted by sunil.23413 on Mon, 07 Oct 2019 06:53:55 +0200

This article covers spring cloud learning sample programs, eureka, feign, rebbion, hystrix, zuul, config, bus usage examples (using svn to manage configuration).

Eureka Registry

Eureka server configuration

@EnableEurekaServer

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false #Is eureka itself registered as an application in the eureka registry?
    fetch-registry: false #When true, it can be started, but an exception is reported: Cannot execute request on any known server
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Eureka client configuration

@EnableDiscoveryClient

spring:
  application:
    name: service-a
eureka:
  client:
    serviceUrl:
          defaultZone: http://Localhost: 8010/eureka/  Eureka Service Registration Address

Load balancing of Ribbon client

When the service is invoked by injecting RestTemplate, the load balance of the client can be achieved by adding annotation @LoadBalanced.

Feign acts as an http client to invoke services

@EnableFeignClients

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

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

Establish an interface that uses @FeignClient (value = service-provider) annotation to indicate the name of the service to be invoked as service-provider, and @RequestMapping to indicate the address of the interface to be invoked in the method. After calling this method in the code, Feign is used as the http client to call the corresponding interface.

Hystrix Fuse Protects Called Service Method

@EnableCircuitBreaker

feign:	
  hystrix:
    enabled: true
hystrix:
  command:
#    IProviderClient#getCar():      # This is commandKey
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 2000   # Fuse condition 1: request timeout time
      circuitBreaker:
        requestVolumeThreshold: 10        # Fuse condition 2: The size of the thread pool (each hystrix command assigns a thread pool to execute, that is, only requests from up to 10 clients at a time are allowed)

If the call fails, the default return result can be set by adding fallback method to the feign interface client. As follows:

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

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

The return value of getCar method in IProviderClientImpl is the default return value.

Zuul Gateway Distribution

@EnableZuulProxy

zuul:
  ignored-services: microservice-provider-user # Services that need to be ignored (which will not be routed after configuration)
  routes:
    first:
      path: /first/**     # This sentence can be omitted if the routing name is configured as first (access http://localhost/first/ca/23)
      url: http://localhost:8080 # Simple Routing
    second:
      path: /second/**
      url: forward:/second   # Forwarding routing
    third:
      path: /third/**
      service-id: service-invoker

Config Configuration Center

Config Server

@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 Client

spring:
  application:
    name: config-client
  cloud:
    config:
      discovery:
        enabled: true       # Find the configuration server based on the service id
        service-id: config-server   # Alternative configuration uri
      fail-fast: true
#      uri: http://localhost:8888
      profile: dev
      name: config-client
      label: trunk         # / trunk/config-client-dev.yml can also be unspecified because the server specifies 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 requests read configuration matching rules:

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

Spring Cloud single sign-on

Authentication Based on Auh2.0 Protocol

Authentication Server

@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     # Represents the scope of permission, optional, user authorization page to choose
      authorized-grant-types: authorization_code #,refresh_token,password,client_credentials     # There are four types of authorization

Resource Server (Used to Provide User Information to Clients)

@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 {
        // Configuration of Resource Server, Client Gets User Information 
        http.antMatcher("/user").authorizeRequests().anyRequest()
            .authenticated();
    }
}

Clients requiring authentication

@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

These are the basic configurations and usage methods of Spring cloud components, which are recorded for query.

The original text was published from the java technology sharing station (jvm123.com): http://jvm123.com/2019/09/springcloud-jian.html

Topics: Spring svn Load Balance RabbitMQ