Writing in the front

Many friends asked me to sort out knowledge points about SpringCloud and SpringCloudAlibaba. After 3 days of collecting and sorting out, Glacier sorted out this 40,000-word learning note about SpringCloud and SpringCloudAlibaba!!

The article has been included:

Github.com/sunshinelyz…

Gitee.com/binghe001/t…

SpringCloud

Service Registry

eureka

Ap high availability distributed fault tolerance

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
eureka:
  instance:
    hostname: eureka7003.com # Eureka server instance name
    instance-id: payment8001 
    prefer-ip-address: true
  client:
    register-with-eureka: false     #false: do not register yourself with the registry.
    fetch-registry: false     #false indicates that my end is the registry and my responsibility is to maintain the service instance, not to retrieve the service
    service-url:
      # cluster points to other Eurekas
      #defaultZone: http://eureka7002.com:7002/eureka/
      # Single is 7001 by itself
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
    #server:
    # Turn off the self-protection mechanism to ensure that unavailable services are kicked out in time
    #enable-self-preservation: false
    #eviction-interval-timer-in-ms: 2000
Copy the code

The Ribbon enables load balancing

@EnableEurekaServer
@EnableDiscoveryClient

@LoadBalanced
public RestTemplate getTemp(a) {
    return new RestTemplate();
}
Copy the code

zookepper

Cp strong uniformly distributed fault tolerance

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.6.1 track</version>
</dependency>spring: application: name: cloud-zoo-consumer-order cloud: zookeeper: connect-string: @ SpringBootApplication @ EnableDiscoveryClient 192.168.10.58:2181Copy the code

consul

Cp strong uniformly distributed fault tolerance

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
spring:
  application:
    name: consul-payment-provider
  cloud:
    consul:
      host: 192.16810.. 58
      port: 8500
      discovery:
        service-name: ${spring.application.name}
@SpringBootApplication
@EnableDiscoveryClient
Copy the code

Service invocation load balancing

Ribbon

The Ribbon switches load rules

  1. Setup configuration on the springBoot package scan outer layer
@Configuration
public class Myrule {
    @Bean
    public IRule initRule(a) {
        return newRandomRule(); }}Copy the code
  1. The startup class loads random methods for the specified service
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = Myrule.class)
Copy the code

OpenFeign

  1. Adding Maven dependencies
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Copy the code
  1. The start class enables Feign
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
Copy the code
  1. Create an interface and register Feign information
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")  // Provider service name
public interface Service {
    @GetMapping(value = "/payment/get/{id}")
    Response<Payment> getPaymentById(@PathVariable("id") Long id);
}
Copy the code
  1. Provide side interface demonstration
@GetMapping(value = "/payment/get/{id}")
public Response<Payment> getPaymentById(@PathVariable("id") Long id) {
    Payment payment = paymentService.getPaymentById(id);

    if(payment ! =null) {
        return Result.success(200."Query successful,serverPort:" + serverPort, payment);
    } else {
        return Result.success(444."No record, query ID:" + id, null); }}Copy the code

OpenFeign Timeout setting

ribbon:
# refers to the time it takes to establish a connection. It is applicable to the time it takes to establish a connection between two ends under normal network conditions
  ReadTimeout: 5000
# refers to the time it takes to read the available resources from the server after the connection is established
  ConnectTimeout: 5000
Copy the code

OpenFeign Log printing function

  1. Configure the Openfeign log level
@Configuration
public class FeignLogConfig {
    @Bean
    public Logger.Level getLevel(a) {
        returnLogger.Level.FULL; }}Copy the code
  1. In the YML project configuration file, configure the log level for the specified Feign interface
logging:
  level:
    ml.ytooo.feignservice.Service: debug
Copy the code

Hystrix service governance

  • When the service is degraded and out of danger, a friendly reminder is returned to prevent the program from being abnormal or blocked
  • The service blows the fuse. When the service capacity is exceeded, a prompt is returned to reject the request
  • Configure the service load limiting gate

Hystrix

Service degradation

When service processing times out or runs abnormally, the startup alternative returns the expected result to the caller

The main method

@EnableCircuitBreaker
Copy the code

A program that needs to be degraded

Among them

  • PaymentInfo_TimeOut is an expected timeout program
  • PaymentInfo_TimeOut_Handler is a timeout alternative
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOut_Handler", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000") })
public String paymentInfo_TimeOut(Integer id) {

    int time = 5;
    try { TimeUnit.MILLISECONDS.sleep(time * 1000); } catch (InterruptedException e) { e.printStackTrace(); }
    return "Thread pool:" + Thread.currentThread().getName() + " paymentInfo_TimeOut,id: " + id + "\t" + "O (studying studying) O ha ha ~" + "Time (seconds):" + time;
}

public String paymentInfo_TimeOut_Handler(Integer id) {
    return "Thread pool:" + Thread.currentThread().getName() + " paymentInfo_TimeOut_Handler,id: " + id + "\t" + "O (╥ man ╥) o";
}
Copy the code

Global degradation processing

Configure defaultFallback to go to its own demotion method, and unconfigured to go to the demotion method specified by default @defaultProperties

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "globle",commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500") })
public class Controller {
    @HystrixCommand
    @GetMapping("/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
        String result = feignService.paymentInfo_TimeOut(id);
        log.info("*****result: " + result);
        return result;
    }
    public String globle(a) {
        return "Global"; }}Copy the code

Configure its provider global degrade configuration through OpenFeign

  1. New feign call interface implementation class FeignServiceImpl, implement all methods and degrade processing
@Service
public class FeignServiceImpl implements FeignService {
    @Override
    public String paymentInfo_OK(Integer id) {
        return "Demote -- paymentInfo_OK";
    }
    @Override
    public String paymentInfo_TimeOut(Integer id) {
        return "Demote -- paymentInfo_TimeOut"; }}Copy the code
  1. Feign calls the interface to add annotations
@FeignClient(value = "CLOUD-PROVIDER-HYSTYRIX-PAYMENT",fallback = FeignServiceImpl.class)
Copy the code

Service fusing

  • When the service is overloaded, the degraded method is directly invoked to reject the connection request and return an exception
  • When requests drop, slowly restore access to the service until full recovery

Configuring service fuses:

If 60% of the 10 requests fail within 10 seconds, the circuit is blown off

HystrixProperty configuration in HystrixCommandProperties. In class class

//===== service meltdown
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = { // @HystrixProperty(name = "CircuitBreaker. Enabled ",value = "true"),// Whether to enable circuitBreaker @hystrixProperty (name = "Value = circuitBreaker. RequestVolumeThreshold", "10"), / / request times @ HystrixProperty (name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), / / time window @ HystrixProperty (name = "circuitBreaker. ErrorThresholdPercentage", value = "60"), / / how many hundred trip}) after failure to
public String paymentCircuitBreaker(@PathVariable("id") Integer id)
{
    if(id < 0)
    {
        throw new RuntimeException("****** ID cannot be negative");
    }
    String serialNumber = IdUtil.simpleUUID();

    return Thread.currentThread().getName()+"\t"+"Call successful, serial number:" + serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) // The method of downgrading after fusing
{
    return "Ids cannot be negative. Please try again later, /(" s" /~~ ID:" +id;
}
Copy the code

Effect: “ID cannot be negative” is returned for consecutive requests using -100. “ID cannot be negative” is returned for consecutive requests using 100

Service current limiting

Use springcloud alibaba sentinel instead

Gateway Gateway

Gateway

Gateway Project Configuration

  1. Adding Maven dependencies
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Copy the code
  1. Remove the following dependencies
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code
  1. Yml Configuration (next step configuration center)
spring:
  application:
    name: cloud-gateaway-gateaway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: payment_get
        # uri: http://127.0.0.1:8001 # single node
          uri : lb://CLOUD-PAYMENT-SERVICE  / # enable Registry cluster
          predicates:
            - Path=/payment/get/**
Copy the code
  1. Register in the Eureka Registry

Gateway Dynamic Routing

  1. Enable the gateway discovery registry service
spring:
  application:
    name: cloud-gateaway-gateaway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
Copy the code

Gateway assertion

An assertion is a condition for determining a forward request

Predicates: - After = 2020-02-21 T15:51:37. 485 + 08:00 Asia/ShanghaiCopy the code
  1. After,Before,Between Sets the validity time of forwarding
public static void main(String[] args) {
    ZonedDateTime now = ZonedDateTime.now();
    System.out.println(now);
}
/ / the T14:2020-08-24 23:57. 171 + 08:00 Asia/Shanghai
Copy the code
  1. Cookie Requests can be accessed only with the specified Cookie
predicates:
  - Cookie=name,ytooo   # key,value
Copy the code
  1. The Header material cookies
predicates:
  - Header=name,ytooo   # key,value
Copy the code

Gateway filter

  1. (Default filters) Official provides a set of filters that allow us to process requests before forwarding them
filters:
  - AddRequestParamter=rowid,1024
Copy the code
  1. Custom filter

Custom global filters

@Component
@Slf4j
public class GatewayLogFilter implements GlobalFilter.Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("= = = = = = = = = = = = = = = = = = = = = into global filter = = = = = = = = = = = = = = = = = = = = =");
        String name = exchange.getRequest().getQueryParams().getFirst("name");
        if (null == name) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder(a) {
        return 0; }}Copy the code

SpringCloud Config Distributed configuration center, BUS message BUS

Distributed configuration center SpringCloud Config

Server Configuration

  1. Create git repository github.com/sunshinelyz…
  2. The introduction of maven
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
Copy the code

3. Start the class for the configuration to take effect

@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class ConfigMain3344 {
    public static void main(String[] args) { SpringApplication.run(ConfigMain3344.class, args); }}Copy the code
  1. Configuration Configuration file
spring:
  application:
    name: cloud-config-center
  cloud:
    config:
      server:
        git:
          uri: https://github.com/sunshinelyz/cloud-config
          search-paths:
            - cloud-config
      label: master
Copy the code
  1. Request access: http://127.0.0.1:3344/master/config-dev.yml

Client Configuration

  1. The introduction of maven
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-client</artifactId>
</dependency>
Copy the code
  1. Configuration Configuration file
spring:
  application:
    name: cloud-condig-client
  cloud:
    config:
      label: master  # branch
      name: config # Config file name
      profile: dev   # version
      uri: http://127.0.0.1:3344 Config server address
Copy the code

Manually refresh the client configuration

Not recommended

Message Bus

Design the logical

Use the message bus to trigger the bus/refresh endpoint on the server to refresh all client config configurations

The initial conditions

Both client and server need to implement Springcloud Config function

Server Configuration

  1. Introducing Maven dependencies
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
Copy the code
  1. Configure message queue information in the configuration file
Configure message queuing
rabbitmq:
  host: 192.16810.. 58
  port: 5672
  username: ytooo
  password: ytooo
Copy the code
  1. Configure BUS exposure information in the configuration file
Configure bus to expose endpoints
management:
  endpoints:
    web:
      exposure:
        include: "bus-refresh"
Copy the code
  1. Previewing configuration files
server:
  port: 3344
spring:
  application:
    name: cloud-config-center
  cloud:
    config:
      server:
        git:
          uri: https://github.com/sunshinelyz/cloud-config
          search-paths:
            - cloud-config
      label: master
  Configure message queuing
  rabbitmq:
    host: 192.16810.. 58
    port: 5672
    username: ytooo
    password: ytooo
eureka:
  instance:
    prefer-ip-address: true
    instance-id: cloud-config-center-3344
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/ #,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
Configure bus to expose endpoints
management:
  endpoints:
    web:
      exposure:
        include: "bus-refresh"
Copy the code

Client Configuration

  1. Introducing Maven dependencies
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
Copy the code
  1. Configure message queue information in the configuration file
Configure message queuing
rabbitmq:
  host: 192.16810.. 58
  port: 5672
  username: ytooo
  password: ytooo
Copy the code
  1. Configuring exposed endpoints
Configure exposed endpoints
management:
  endpoints:
    web:
      exposure:
        include: "*"
Copy the code
  1. Call the configuration class to add @refreshScope
@RestController
@RefreshScope
public class Controller {
    @Value("${config.info}")
    private String configInfo;
    @GetMapping(value = "/test")
    public String test(a) {
        returnconfigInfo; }}Copy the code

Refresh the configuration

POST request config server http://127.0.0.1:3344/actuator/bus-refresh

Refresh the success

Designated notice

POST request config server http://127.0.0.1:3344/actuator/bus-refresh/ {destination}

Destination: Registry service name: port number

🌰 : http://127.0.0.1:3344/actuator/bus-refresh/cloud-condig-client:3366

SpringCloud Stream message driver

Message-driven, unifying the differences in various message-oriented middleware, providing a unified and simple call method, shielding the specific call implementation of message-oriented middleware

SpringCloud Stream Message provider project configuration (easy to use)

  1. Adding Maven dependencies
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
Copy the code
  1. Config file adds the Stream configuration
spring:
  application:
    name: cloud-stream-provider
  cloud:
    stream:
      binders: Configure the rabbitMQ service to bind to rabbitMQ.
        defaultRabbit: # represents the name of the definition used for binding consolidation
          type: rabbit Message component type
          environment: Set the environment configuration for RabbitMQ
            spring:
              rabbitmq:
                host: 192.16810.. 58
                port: 5672
                username: ytooo
                password: ytooo
      bindings: # Service integration processing
        output: This name is the name of a channel
          destination: studyExchange # indicates the Exchange name definition to use
          content-type: application/json # set message type to JSON and text to "text/plain"
          binder: defaultRabbit Set the specific Settings for the message service to bind
Copy the code
  1. Define the message push pipeline
@EnableBinding(Source.class) // Define the message push pipeline
public class MsgProviderImpl implements MsgProvider {}Copy the code
  1. Define the message sending pipeline
@Autowired
private MessageChannel out; // Define the message sending pipeline
Copy the code
  1. Build message entity and send it
Message<String> message = MessageBuilder.withPayload(msg).build();
out.send(message);
Copy the code
  1. Message receiver YML configuration
spring:
  application:
    name: cloud-stream-rabbitmq-consumer
  cloud:
    stream:
      binders: Configure the rabbitMQ service to bind to rabbitMQ.
        defaultRabbit: # represents the name of the definition used for binding consolidation
          type: rabbit Message component type
          environment: Set the environment configuration for RabbitMQ
            spring:
              rabbitmq:
                host: 192.16810.. 58
                port: 5672
                username: ytooo
                password: ytooo
      bindings: # Service integration processing
        input: This name is the name of a channel
          destination: studyExchange # indicates that the Exchange name definition to be used must be the same as the provider
          content-type: application/json # set message type to JSON and text to "text/plain"
          binder: defaultRabbit Set the specific Settings for the message service to bind
Copy the code
  1. The configuration of the receiver listening interface
@EnableBinding(Sink.class)
public class ReceiveMsgImpl implements ReceiveMsg {}Copy the code
  1. Receiver’s note
@StreamListener(Sink.INPUT)
public void receive(Message<String> message) {
    System.out.println("Customer service 8803 received a message:" + message.getPayload());
}
Copy the code

SpringCloud Stream grouped consumption & Persistence

  • Messages are re-consumed for different groups (re-consumed)
  • Within the same group, services compete and are consumed only once (cluster environment, avoiding repeated consumption)

Group profile configuration

Input: # This name is the name of a channel. Destination: studyExchange # Specifies the name of the Exchange to be used. Binder: defaultRabbit binder: defaultRabbit group: ytoooCopy the code

Group Group persistence

If no group is configured, unconsumed services will not be automatically obtained after the service is restarted. If a group is configured, unconsumed messages will be automatically obtained after the service is restarted

Sleuth Distributed request link tracing

Add dependencies to the service

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
Copy the code

Modify the application.yml configuration file and add the following

spring:  
  zipkin:
    base-url: http://localhost:9411
  sleuth:
    sampler:
      probability: 1 The sampling rate value is between 0 and 1, where 1 indicates all collection
Copy the code

SpringCloud Alibaba

Nacos Registry

Add the dependent

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code

Project profile

spring:
  application:
    name: cloudalibaba-nacos-consumer-order
  cloud:
    nacos:
      discovery:
        server-addr: 192.16810.. 58: 8848
Copy the code

Main program startup

@EnableDiscoveryClient
Copy the code

Invoke the service with Openfeign

Nacos Config Configuration center

  1. Adding Maven dependencies
<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-alibaba-nacos-config</artifactId>
</dependency>
Copy the code
  1. Add configuration center configuration to bootstrap.yml
spring:
  application:
    name: cloudalibaba-nacos-config-cclient
  cloud:
    nacos:
      discovery:
        server-addr: 192.16810.. 58: 8848
      config:
        server-addr: 192.16810.. 58: 8848
        file-extension: yaml
  profiles:
    active: dev
Copy the code
  1. The business class adds @refreshScope to refresh automatically
@RestController
@RefreshScope
public class Controller {
Copy the code
  1. Configuration format in the configuration file

In Nacos Spring Cloud, the full format of dataId is as follows:

The prefix – {prefix} – prefix – {spring. Profiles. The active}. ${file – the extension}

  • Prefix for spring. The default application. The name of the value, but can be by spring configuration items. The cloud. Nacos. Config. The prefix to configuration.
  • Spring.profiles. active is the profile corresponding to the current environment. For details, refer to the Spring Boot documentation. Note: When spring.profiles. Active is null, the corresponding connector – will also not exist and the dataId concatenation format becomes prefix.{prefix}.prefix.{file-extension}
  • File – exetension as the configuration of content data format, can be configured a spring. Cloud. Nacos. Config. The file – the extension to the configuration. Currently, only properties and YAML types are supported.

In this example, the file name is cloudbaba-nacos-config-cclient-dev.yaml

Nacos config Configures the central classification

Nacos uses three layers to isolate services

  • NameSpace Specifies the NameSpace. The default value is public
  • Group Group, DEFAULT_GROUP by default
  • Service Micro Service: A Service can contain multiple clusters. The DEFAULT Cluster is DEFAULT. Regional Dr Can be implemented by region

Group information and namespace are configured in YML

spring:
  application:
    name: cloudalibaba-nacos-config-cclient
  cloud:
    nacos:
      discovery:
        server-addr: 192.16810.. 58: 8848
      config:
        server-addr: 192.16810.. 58: 8848
        file-extension: yaml
        group: dev
        namespace: a2438b02-01e1-4a3c-959c-600d93183d22 Use the namespace ID
Copy the code

Sentinel service fuse and downgrade

  • Individual component
  • Can interface, fine – grained unified configuration

The Sentinel service is configured by the managed party

  1. Maven rely on
<dependency>
  <groupId>com.alibaba.csp</groupId>
  <artifactId>sentinel-datasource-nacos</artifactId>   <! -- Sentinel Persistence -->
</dependency>
<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
Copy the code
  1. Sentinel Dashboard monitoring is configured in YML
spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: 192.16810.. 58: 8848
    sentinel:
      transport:
        dashboard: 192.16810.. 58: 8888 # Sentinel Dashboard address
Copy the code

Configure the degradation method: This method applies only to the specified traffic limiting hotspot configured on the page

@GetMapping(value = "/hot")
@SentinelResource(value = "hot", blockHandler = "deal_hot")
public String hot(String p1, String p2) {
    return "= = = = = = = = = = = = = = = = = = = = = = = = = = hotspot by = = = = = = = = = = = = = = = = = = = = = = = = = =";
}

public String deal_hot(String p1, String p2, BlockException e) {
    return "= = = = = = = = = = = = = = = = = = = = = = = = = = hot down = = = = = = = = = = = = = = = = = = = = = = = = = =";
}
Copy the code

Seata distributed transactions

  • Global transaction ID
  • TC transaction coordinator maintains global and branch transaction state and drives commit or rollback of global transactions
  • The TM transaction manager defines the scope of the global transaction and starts the global transaction. Commit or roll back the global transaction
  • The RM resource manager manages the resources for branch transaction processing, talks to TCS to register branch transactions and report the status of branch transactions, and drives the commit or rollback of branch transactions

If you have any questions, you can leave a comment below or add me to wechat: SUN_shine_LYz. I will pull you into the group. We can exchange technology together, advance together, and make great force together