springboot2.0 new version of springcloud microservice: Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin

sb2.0 new version of springcloud microservice: Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin

The spring boot version is 2.0.3 Release, the spring cloud version is Finchley RELEASE

Aiprose personal essay online, website: aiprose com Click to access

This article is spring boot 2 The upgraded version of X is specially posted on springcloud. Because the previous version has been updated for a long time, many people commented on whether a new version can be produced. We must pay attention to this. This is springboot2 X version, springboot1 X please refer to Click to view the article , the basic components remain unchanged, that is, upgrade the jar package version, mainly the use of hystrix dashboard changes a little. It should also be noted that the default use of sc is Eureka 1 9. X version, we must be main, do not manually change to 2 X version, because 2 Version x has not been officially released, and development has stopped. The official is still actively maintaining version 1 X Version (not the closed source of network transmission).

I believe that many small partners have used or are ready to use springcloud microservices. Next, build a microservice framework for you, and you can expand it yourself later. A small case will be provided: service providers and service consumers. Consumers will call the provider's services. All new projects are downloaded using springboot with source code. It is recommended to download using coding address, because branches can be switched and can be updated in time later.

coding warehouse address (recommended download): coding address Remote configuration warehouse address Remote configuration warehouse address

If you have any questions, please comment below, or add group communication in 200909980. Or pay attention to the ending of the article, WeChat official account, private letter background.

eureka / consult / zookeeper: Service Discovery (select one according to the situation, and eureka has declared the source closed) Hystrix: circuit breaker Zuul: intelligent routing Ribbon/Feign: client load balancing (Feign uses more) Turbine & hystrix dashboard: cluster monitoring Spring cloud config: get configuration files remotely

Next, we start to build the project. First, we go to a website provided by spring to quickly build the springboot project, Click to access , I use gradle here. If you like maven, you can go there http://mvnrepository.com/ View the corresponding dependencies, Click me to visit.

1, Build Eureka server service SC Eureka server

Use spring cloud consumer as service discovery. Please refer to Click to view using springcloud consumer as service discovery

As the core of service discovery, Eureka server is built first. All subsequent services must be registered with Eureka server, which means to tell Eureka server what its service address is. Of course, you can also use zookeeper or spring consumer.

  • 1. Modify build Gradle file

If it is a maven project, please modify POM xml

//Join Alibaba's private server warehouse address
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
//Join dependency	
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-server')
//Security is added because the user name and password are required to access Eureka server for security
compile('org.springframework.boot:spring-boot-starter-security')

There are several points that need to be modified. Let's take a look at the corresponding picture, that is, when springboot is packaged, it will prompt that the main class cannot be found.

  • 2. Modify application yml, yml is recommended.
server:
  port: 8761
eureka:
  datacenter: trmap
  environment: product
  server:
      # Turn off self-protection
      enable-self-preservation: false
      # Clean up server
      eviction-interval-timer-in-ms: 5000
  client:
    healthcheck:
      enabled: true
    service-url:
      defaultZone: http://root:booszy@localhost:8761/eureka/
    register-with-eureka: false
    fetch-registry: false
spring:
  security:
    basic:
      enabled: true
    user:
      name: root
      password: booszy
  • 3. Modify the main class of the program. It is recommended to modify the class name, add the @ EnableEurekaServer annotation of eureka, and then run the main method.
@EnableEurekaServer
@SpringBootApplication
public class Sb2scEurekaApplication {
	public static void main(String[] args) {
		SpringApplication.run(Sb2scEurekaApplication.class, args);
	}
}

http://localhost:8761/ This is the page address of Eureka server. The password is in the yml configuration file. Here, it shows that Eureka server has been built. Simply, this step must be successful, otherwise the following steps cannot continue. The latter is basically similar.

2, Build config server service SC config server

Spring cloud config server is used to dynamically pull down the configuration file of the remote git warehouse so that the configuration file can be maintained dynamically. Of course, you can also choose a local warehouse.

Create a new springboot project, modify the maven private server address, and add dependencies.

  • 1. Modify build Gradle file
compile('org.springframework.cloud:spring-cloud-config-server')
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
//User name and password are also required to connect to config server
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-actuator')
  • 2. Modify application YML file
server:
  port: 8800
spring:
  security:
    basic:
      enabled: true
    user:
      name: root
      password: booszy
  application:
    name: sc-config-server
  cloud:
    config:
      server:
        git:
          uri: https://git.coding.net/yirenyishi/springcloud-config-profile
          searchPaths: '{application}'
eureka:
  client:
    service-url:
      defaultZone: http://root:booszy@localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    appname: sc-config-server
  • 3. Modify startup class

To modify the startup class, add these three annotations. Because you want to register with Eureka server, you need the @ EnableDiscoveryClient annotation

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

Then run the startup springboot project. After successful startup, visit the page of eureka and find that SC config server has been registered on it. If an error is reported during startup, please check the error information.

3, Build a service SC provider

To write a service provider to provide services for consumers below, spring weblux (spring's new non blocking framework) is used, not spring MVC. Of course, you still use what your company uses.

  • Note: except for application XML, you also need a bootstrap YML, because bootstrap The loading sequence of YML is in application Before XML, the service registration and config configuration must be placed in bootstrap. XML yml.
    1. Modify build Gradle file
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.boot:spring-boot-starter-webflux')
compile('org.springframework.boot:spring-boot-starter-actuator')
  • 2. Write the configuration file bootstrap yml

**Note: except for application XML, you also need a bootstrap yml*

application.xml is placed in the remote warehouse address. You can directly go to my remote warehouse and query according to the project name (SC provider config). Warehouse address of configuration file: Click to access.

eureka:
  client:
    service-url:
      defaultZone: http://root:booszy@localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    appname: sc-provider

spring:
  application:
    name: sc-provider
  cloud:
    config:
      discovery:
        enabled: true
        service-id: sc-config-server
      fail-fast: true
      username: root
      password: booszy
      profile: csdn
  • 3. Write code

Write main class

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

Create a new IndexController for testing. This is just for testing. The case code uses weblux. If you want to use spring MVC, you can modify the jar package dependency.

@RestController
@RequestMapping("test")
public class IndexController {
	//Returns an entity
    @GetMapping("{msg}")
    public Mono<String> sayHelloWorld(@PathVariable("msg") String msg) {
        System.out.println("come on " + msg);
        return Mono.just("sc-provider receive : " +msg);
    }
	//Returns a list
    @GetMapping("list")
    public Flux<Integer> list() {
        List<Integer> list = new ArrayList<>();
        list.add(8);
        list.add(22);
        list.add(75);
        list.add(93);
        Flux<Integer> userFlux = Flux.fromIterable(list);
        return userFlux;
    }
}

Run the springboot project and go to Eureka server to check whether it is registered.

Our SC provider has been registered with eureka. The access interface is successful.

4, Build a consumer service SC consumer

Consumers want to access the services of the service provider. Here, they use RestTemplate/feign to request the restful interface, use ribbon for client load balancing, and hystrix for error handling. Feign and ribbon can be selected. In the case, both ribbon and feign can be used. Or the familiar formula and taste, create a new springboot project and add project dependencies.

  • 1. Modify build Gradle file
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.boot:spring-boot-starter-webflux')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.cloud:spring-cloud-starter-openfeign')
compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix')
  • 2. Modify bootstrap YML file

application.yml is in Git warehouse. Please go to git warehouse to check.

eureka:
  client:
    service-url:
      defaultZone: http://root:booszy@localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    appname: sc-consumer

spring:
  application:
    name: sc-consumer
  cloud:
    config:
      discovery:
        enabled: true
        service-id: sc-config-server
      fail-fast: true
      username: root
      password: booszy
      profile: csdn
#New configuration, otherwise the dashboard cannot find hystrix stream
management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 3. Write code

Startup class code

@RibbonClient specifies the load balancing type used by the service. If name does not specify the service, load balancing is turned on for all services. It can also be configured in yml. @EnableHystrix supports hystrix to open the circuit breaker. If the failure parameter exceeds a certain parameter within the specified time, the circuit breaker will be opened. Instead of initiating a request, it will directly enter the error handling method.

@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrix
@SpringBootApplication
public class Sb2scConsumerApplication {
	// ribbon needs configuration and load balancing
	@Autowired
	private RestTemplateBuilder builder;

	// ribbon needs configuration and load balancing
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return builder.build();
	}
	public static void main(String[] args) {
		SpringApplication.run(Sb2scConsumerApplication.class, args);
	}
}

1.ribbon case

You do not need to rely on the ribbon separately. Create a new ribbon controller The ribbon is a pit and cannot accept List type. It should be received by array. @HystrixCommand(fallbackMethod="fallbackMethod") If the request fails, it will enter the fallbackMethod method, which requires that the parameters and return values be consistent with the callback method.

@RestController
public class RibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/ribbon/{wd}")
    @HystrixCommand(fallbackMethod="fallbackMethod")
    public Mono<String> sayHelloWorld(@PathVariable("wd") String parm) {
        String res = this.restTemplate.getForObject("http://sc-provider/test/" + parm, String.class);
        return Mono.just(res);
    }

    public Mono<String> fallbackMethod(@PathVariable("wd") String parm) {
        return Mono.just("fallback");
    }

Run the springboot project to see if it is registered with Eureka server.

After successful registration, access the interface and test whether it is correct.

The ribbon is so simple to use. The ribbon comes with springboot, so you don't need to add dependencies separately.

2.feign case

In the actual development, feign still uses a lot, and the bottom layer of feign still uses ribbon. Without much nonsense, go straight to the next step and use feign to access the service provider in the service consumer.

  • 1 configuration file
ribbon:
  ReadTimeout:  30000
  ConnectTimeout:  15000
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000

Feign's default request timeout is 1s, so the timeout problem often occurs. I set 10s here. Because my database server is in the United States, sometimes the request is relatively slow. The request time of ribbon should also be set, because feign uses ribbon. Here is application A short paragraph in the YML file

  • 2 coding

1. Main class annotation

@EnableFeignClients @EnableCircuitBreaker @EnableHystrix

All three should be. hystrix is mainly used as a circuit breaker, which will enter the fallback of fein. The main class code has been posted on it

2. Write feign interface, mfeignclient class

Name is the name of the service to be requested. The service provider is requested here fallback refers to the class that enters the circuit breaker when the request fails, which is the same as using ribbon. Configuration is some configuration of feign, such as encoder, etc.

@FeignClient(name = "sc-provider",fallback = MFeignClientFallback.class, configuration = MFeignConfig.class)
public interface MFeignClient {
    // This is the address of the requested microservice, that is, the address of the provider
    @GetMapping(value = "/test/{msg}")
    String sayHelloWorld(@PathVariable("msg") String msg);

    @GetMapping(value = "/test/list")
    List<Integer> list();

    @GetMapping(value = "/test/list")
    Integer[] array();
}
  • 3 MFeignConfig. Configuration of class feign

The print log level of feign is configured here

@Configuration
public class MFeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}
  • 4 MFeignClientFallback.class, circuit breaker callback method

The circuit breaker needs to implement the MFeignClient interface defined above. If the request fails, the method here will be called back when entering the circuit breaker.

@Component
public class MFeignClientFallback implements MFeignClient{
    @Override
    public String sayHelloWorld(String msg) {
        return "fallback";
    }

    @Override
    public List<Integer> list() {
        return new ArrayList<>();
    }

    @Override
    public Integer[] array() {
        return new Integer[0];
    }
}
  • 5 use feign in controller
@RestController
public class FeignController {

    @Autowired
    private MFeignClient feignClient;

    @GetMapping("/feign/{wd}")
    public Mono<String> sayHelloWorld(@PathVariable("wd") String parm) {
        String result = feignClient.sayHelloWorld(parm);
        return Mono.just(result);
    }

    @GetMapping("/feign/list")
    public Flux<Integer> list() {
        List<Integer> list = feignClient.list();
        Flux<Integer> userFlux = Flux.fromIterable(list);
        return userFlux;
    }

    @GetMapping("/feign/array")
    public Flux<Integer> array() {
        Integer[] arrays = feignClient.array();
        Flux<Integer> userFlux = Flux.fromArray(arrays);
        return userFlux;
    }
}

5, Routing forwarding and load balancing with zuul

These micro services are hidden in the back end. Users can't see them or don't contact them directly. You can use nginx or zuul for routing forwarding and load balancing. Zuul load balancing uses ribbon by default.

  • 1. Modify build Gradle file
	compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
	compile('org.springframework.cloud:spring-cloud-starter-config')
	compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')
	compile('org.springframework.boot:spring-boot-starter-actuator')
  • 2. Modify bootstrap yml

It's still the original formula, application YML in git warehouse

eureka:
  client:
    service-url:
      defaultZone: http://root:booszy@localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    appname: sc-zuul

spring:
  application:
    name: sc-zuul
  cloud:
    config:
      discovery:
        enabled: true
        service-id: sc-config-server
      fail-fast: true
      username: root
      password: booszy
      profile: csdn
  • 3. Startup class

@The RefreshScope annotation is when the application When the YML configuration file changes, there is no need to restart manually. Calling localhost:8400/refresh will load the new configuration file. Of course, the visiting customers will not affect using the old configuration file, because it is not restarted, and later users will use the new configuration file. Note that the refresh of this piece should be requested by post.

@EnableDiscoveryClient
@SpringBootApplication
@EnableZuulProxy
@RefreshScope
public class Sb2scZuulApplication {
	public static void main(String[] args) {
		SpringApplication.run(Sb2scZuulApplication.class, args);
	}
}

Start the springboot project and access Eureka server

At this time, we will access microservices through zuul instead of directly accessing microservices. Should access address http://localhost:8400/sc-consumer/feign/list, you need to change this to your zuul address.

However, some people will say that the user request will not be too long in the future, which is disgusting, so the access address can be modified through configuration.

zuul:
  routes:
    springcloud-consumer-config: /consumer/**
    springcloud-provider-config: /provider/**

In application Adding such a configuration to YML is actually the reverse proxy in nginx. Use a short to proxy this micro service. At this time, we can visit like this http://localhost:8400/consumer/feign/list , isn't it a lot shorter

6, Cluster monitoring with hystrix turbine dashboard

In the production environment of the project, the traffic of each service is blocked. Some services have a large traffic. Sometimes some services hang up and can't continue the service. We don't know when it needs to be restarted, so we need to use the hystrix turbine dashboard to monitor all micro services. We can see the real-time traffic of this interface, And health. Create a new springboot project, the old routine, and add the following dependencies

  • 1 add dependency
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix')
compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix-dashboard')
compile('org.springframework.cloud:spring-cloud-starter-netflix-turbine')
  • 2. Modify application YML profile Note: it is application YML, bootstrap is not required here yml
server:
  port: 8900
eureka:
  client:
    service-url:
      defaultZone: http://root:booszy@localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    appname: sc-dashboard
turbine:
  aggregator:
    clusterConfig: default
  appConfig: sc-consumer
  clusterNameExpression: "'default'"
spring:
  application:
    name: sc-dashboard
#management:
#  endpoints:
#    web:
#      exposure:
#        include: '*'

appConfig is followed by the service name registered on eureka to be detected, which must have

  • 3. Modify main class

@EnableTurbine, @ EnableHystrixDashboard, none less

@EnableDiscoveryClient
@SpringBootApplication
@EnableTurbine
@EnableHystrixDashboard
public class Sb2scDashboardApplication {
	public static void main(String[] args) {
		SpringApplication.run(Sb2scDashboardApplication.class, args);
	}
}
  • 4 access test

This port is 8900, access address http://localhost:8900/hystrix , see the following page.

Then enter the URL in the URL input box http://localhost:8900/turbine.stream , click monitor stream. When you first open it, it may be empty and have nothing, which doesn't mean you're wrong. At this time, you access the interface of consumer services, such as http://localhost:8400/consumer/feign/list , visit the console several times, and then see if a monitoring panel appears on the console. If not, it will be refreshed once. If it doesn't appear all the time, there should be a problem with the configuration.

7, Using sleuth+zipkin to implement link tracking service

When using microservices, we find that sometimes troubleshooting is difficult, so we give you the whole link tracking, which is convenient to know which service calls which service has a problem. Because some projects may serve more.

  • 1 add dependency

Create a new springboot project Although other services call zipkin by hard coding instead of dynamically passing through the service address from eureka, consider registering zipkin with eureka.

compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
compile group: 'io.zipkin.java', name: 'zipkin-server', version: '2.9.3'
compile group: 'io.zipkin.java', name: 'zipkin-autoconfigure-ui', version: '2.9.3'
compile('org.springframework.boot:spring-boot-starter-actuator')

If the prompt log4j has conflict, exclude the dependency

configurations {
	compile.exclude module: 'log4j'
	compile.exclude module: 'slf4j-log4j12'
	compile.exclude module: 'spring-boot-starter-logging'
}
  • 2. Modify the application configuration file
server:
  port: 9411
spring:
  application:
    name: sc-sc-zipkin
  profiles:
    active: csdn
eureka:
  client:
    service-url:
      defaultZone: http://root:booszy@localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    appname: sc-zipkin
management:
  metrics:
    web:
      server:
        auto-time-requests: false
  • 3 main class annotation addition

@EnableZipkinServer mainly uses this annotation Access after starting the service http://localhost:9411 , you can open the console page of zipkin. At this time, there should be nothing

@EnableDiscoveryClient
@SpringBootApplication
@EnableZipkinServer
public class Sb2scZipkinApplication {
	public static void main(String[] args) {
		SpringApplication.run(Sb2scZipkinApplication.class, args);
	}
}
  • 4 calls in other services

Here, we add the following dependencies to both consumer services and provider services

compile('org.springframework.cloud:spring-cloud-starter-sleuth')
compile('org.springframework.cloud:spring-cloud-starter-zipkin')

Then modify the configuration file, bootstrap yml, The zipkin address is hard coded. At present, we haven't found out how to dynamically obtain it from the service registry eureka. In the future, there will be solutions and posts will be updated sleuth is the configuration extraction rate, which can be configured or not

spring:
  zipkin:
    base-url: http://localhost:9411
  sleuth:
    sampler:
      percentage: 1.0

Start the service, and then access the interface of the consumer service. At this time, access the zipkin console http://localhost:9411

Click dependency analysis to see the calling service chain. Because only two services are involved, there are only two. In the actual production environment, there may be many services, which will look very intuitive at that time.

Added by discostudio on Sun, 23 Jan 2022 07:09:23 +0200