The five core components of spring cloud are brother Jun and brother Hou

Keywords: Java Spring Spring Boot Spring Cloud

Summary of spring cloud notes of Leyou project

The mapper module of ly item commodity contains datasource

Ly Cart: Shopping Cart module

Ly registry: registry server, other modules are clients

Ly API gateway: routing gateway

Ly feign: remote call

Registration Center Eureka, ly registry server

Lyregister the Module as the server

The server can be configured

server:
  port: 10086

spring:
  application:
    name: ly-registry

eureka:
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:${server.port}/eureka

  server:
    enable-self-preservation: false #Turn off self-protection
    eviction-interval-timer-in-ms: 5000 #Clean up the service list every 5 seconds
package com.yunhe;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class LyRegistry {
    public static void main(String[] args) {
        SpringApplication.run(LyRegistry.class,args);
    }
}


Use ly user as the client for relevant tests:

package com.yunhe;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients  //Enable feign function
public class LyUserApplication {
    public static void main(String[] args) {
        SpringApplication.run(LyUserApplication.class,args);
    }
}

Add dependencies on related client implementations:

 <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--feign Implement remote call ly-item-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

Client configuration

server:
  port: 10010

spring:
  application:
    name: item-service


  datasource:
    url: jdbc:mysql://localhost:3306/leyou?characterEncoding=UTF-8&useSSL=false
    username: root
    password: roothouzhicong

    hikari:
      maximum-pool-size: 30
      minimum-idle: 10

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    lease-renewal-interval-in-seconds: 5 #Send heartbeat every 6 seconds
    lease-expiration-duration-in-seconds: 10 #Expire without sending in 10 seconds
    prefer-ip-address: true
    ip-address: 127.0.0.1
    instance-id: ${spring.application.name}:${server.port}
    
 # Configure Ribbon
item-service: #Load balancing configuration in feign
  ribbon:
    ConnectTimeout: 250 # Ribbon connection timeout
    ReadTimeout: 3000 # Ribbon data read timeout
    OkToRetryOnAllOperations: true # Retry all operations
    MaxAutoRetriesNextServer: 1 # Number of retries to switch instances
    MaxAutoRetries: 1 # Number of retries on the current instance

feign:
  hystrix:
    enabled: true # Turn on the fusing function of Feign, which is off by default
    

Feign implements remote call

The ly user module calls ly item

  1. Add feign dependency in pom.xml file of ly user

  2. Add * * @ EnableFeignClients * * annotation on LyApplication startup class of ly user

  3. Create an itemClient interface under the client

  4. @RequestMapping("brand")
    

Add the path of the request to be used by the front end.

  1. Add the related methods defined in the Service interface.
  2. Add * * @ FeignClient(name = "item service") * * (item service is spring. Application. Name = item service in the ly item module)
  3. Since it has not been optimized, we can copy and paste all pojo classes first
  4. Create a BrandController to test the front end, and input the request of this test class

itemClient:

package com.yunhe.client;

import com.yunhe.pojo.Brand;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//Note: do not write @ RequestMapping on the class
@FeignClient(name = "item-service",fallback = ItemClientFallback.class)
public interface ItemClient {

    @GetMapping("brand")
    public List<Brand> listAll();


}
@RestController
public class UserController {

    @Autowired
    private ItemClient itemClient;

    @GetMapping
    public List<Brand> queryAllBrands(){
        return itemClient.listAll();
    }
}

Ribbon load balancing

  1. You can know that feign, Eureka and zuul already have their own ribbon and Hystrix, so there is no need to introduce dependency

Hystrix fuse

feign has its own fuse, but it is closed by default and needs to be opened manually

To make the ly user module call the ly item module, feign and hystrix are required, and the hystrix steps are as follows:

  1. yml file plus:
feign:
	hystrix:
	enabled: true #Open the fuse
  1. Create the client package and then create the following class. / / Note: do not write @ RequestMapping on the class. The @ GetMapping("brand") here is the same as the request of the controller test in ly item.
package com.yunhe.client;

import com.yunhe.pojo.Brand;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//Note: do not write @ RequestMapping on the class
@FeignClient(name = "item-service",fallback = ItemClientFallback.class)
public interface ItemClient {

    @GetMapping("brand")
    public List<Brand> listAll();


}

  1. Create an ItemClientFallback implementation class: the disconnection of the ly item service will not affect the execution of the ItemClientFallback method
package com.yunhe.client;

import com.yunhe.client.ItemClient;
import com.yunhe.pojo.Brand;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Component
public class ItemClientFallback implements ItemClient {
    @Override
    @GetMapping("brand")
    public List<Brand> listAll() {
        System.out.println("The service is broken, woo woo...");
        return null;
    }
}

zuul gateway

  1. Create a separate module ly API gateway, and all port numbers will be processed by zuul.
  2. Of course, all other modules are the clients of the registry. You need to add * * @ EnableDiscoveryClient on the main configuration file**
  3. **Introducing the dependency of gateway, * * also needs to introduce the dependency of eureka client
<!--zuul gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>


        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  1. Add * * @ enablezulproxy * * gateway proxy annotation on the startup class

  2. Configure the gateway in the application.yml file of ly API gateway. Note that the item service under routes is the name of spring.application.name in the configuration file

zuul:
	prefix: /api #Add routing prefix
	retryable: true
	routes:
		item-service: /item/** #Goods and services
		user-service: /user/** #User micro service
		cart-service: /cart/** #Shopping Cart Service
  1. All profile information of the gateway
server:
  port: 10000

spring:
  application:
    name: api-gateway

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    lease-renewal-interval-in-seconds: 5 #Send heartbeat every 6 seconds
    lease-expiration-duration-in-seconds: 10 #Expire without sending in 10 seconds
    prefer-ip-address: true
    ip-address: 127.0.0.1
    instance-id: ${spring.application.name}:${server.port}
zuul:
  prefix: /api # Add routing prefix
  retryable: true #Can I try again when the gateway is not connected
  routes:
    item-service: /item/**  #All requests under commodity microservices / item
    user-service: /user/**  #User micro service
    cart-service: /cart/** #Shopping cart micro service

ribbon:
  ConnectTimeout: 60000 # Connection timeout (ms)
  ReadTimeout: 60000 # Communication timeout (ms)
  OkToRetryOnAllOperations: true # Retry all operations
  MaxAutoRetriesNextServer: 1 # Number of retries for different instances of the same service
  MaxAutoRetries: 1 # Number of retries for the same instance
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMillisecond: 10000 # Fuse timeout: 10000ms
  1. Add, delete, modify and query the ly item through the gateway.

    http://localhost:10000/api/item/brand The effect is the same as that without gateway access http://localhost:10010/brand

  2. zuul has its own hystrix and Ribbon functions, which need to be enabled through the configuration file

  3. The gateway can be configured for filtering

package com.yunhe.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
//Note that you need to add this @ Component component 
@Component
public class LoginFilter extends ZuulFilter{
    /**
     * - pre: The request is executed before it is routed
     * - routing: Called when routing a request
     * - post: Call after routing and errror filter
     * - error: An error occurred while processing the request
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    //The smaller the number, the higher the priority
    @Override
    public int filterOrder() {
        return 1;
    }

    //Whether to filter true filter false do not filter
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //run() filter method
    @Override
    public Object run() throws ZuulException {
        System.out.println("zuul filter Executed.....");
        return null;
    }
}

Posted by pimp3679 on Tue, 05 Oct 2021 11:14:53 -0700