13.Spring-Cloud-Feign configuration in Ribbon and Hystrix

feign the configuration of ribbon

Mainly in the ribbon-core.jar Files, com.netflix.client.config package, which configure the default class DefaultClientConfigImpl
easiest way to configure the client and the load balancer is the property meets certain format:
. <ClientName> < namespace>. <propertyName> = < value>
may be defined as a property class path or file system attribute
default, "ribbon" should be namespace.
If no attribute is specified client, com.netflix.client.ClientFactory will still create the client and load balancer for all required attributes. The default value is specified as constants in this class.
If a property is missing clientName, then it will be interpreted as a client for all the properties. For example
ribbon.ReadTimeout = 1000
This will all clients to establish a default ReadTimeout property.
You can also be programmed by setting properties of examples constructed DefaultClientConfigImpl.
If you want to define attributes in different namespace, e.g. "foo"
myclient.foo.ReadTimeout = 1000

feign the configuration of hystrix

Before hystrix be configured first to confirm feign.hystrix.enabled parameter set to true (opened Hystrix fuse protection), otherwise parameter setting close Feign client hystrix, the main configuration is configured to HystrixCommand is in hystrix com.netflix.hystrix.HystrixCommandProperties -core.jar the class file, as configured for certain parameters screenshot

As timeout global configuration:

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds = 5000 // default is 1000ms That 1s

The caller service

   The caller transformation services

    controller

 

/ ** Service retry mechanism main presentation ribbon thread sleep, when more than consumer connection timeout configuration, a second reconnection

* Does not receive parameters
* @return
* @throws InterruptedException 
*/
@SuppressWarnings("deprecation")
@RequestMapping(value = "/hello1", method = RequestMethod.GET)
public String hello() throws InterruptedException {
ServiceInstance instance = client.getLocalServiceInstance();
logger.info("/hello1,host:{},service_id:{}",instance.getHost(),instance.getServiceId());
//测试超时 
int sleep = new Random().nextInt(3000);
logger.info("sleep time:{}",sleep);
Thread.sleep(sleep);
return "hello spring cloud";
}

 

   Start class service consumers

Package Penalty for com.niugang;


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

/**
 * Feign consumer version
 * 
 * @Author niugang
 *
 */
@SpringBootApplication
@EnableDiscoveryClient
// scanning declares them feign interface of the client (by @FeignClient) 
@EnableFeignClients
 public  class the Application {
 public  static  void main (String [] args) {
SpringApplication.run(Application.class, args);
}
}

 

   Configuration

# Specify the name of the follow-up of micro-services only need to use this name when calling the service can be accessed
spring.application.name=feign-consumer
server.port=9001
# Registration Center Address
eureka.client.serviceUrl.defaultZone=http://testhost:8000/eureka/


####################### ribbon configuration ######################### ###
#ribbon, the development of service configuration, Service - the Provide service name
service-provide.ribbon.ConnectTimeout=500
service-provide.ribbon.ReadTimeout=2000
service-provide.OkToRetryOnAllOperations=true
# Retry strategy to try to access a preferred example
service-provide.ribbon.MaxAutoRetries=1
# Try replacing two examples retry
service-provide.ribbon.MaxAutoRetriesNextServer=2
##################### hystrix placed ########################### ###
# Opened feign client Hystrix support that opened fuses
feign.hystrix.enabled=true

 

   Call service interface

package com.niugang.service;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.niugang.entity.User;
import com.niugang.fallback.ServiceProvideFallBack;
/**
 * Define the service binding interfaces
 *
 * / 
// declaration calling service
 // value: name calling services
 // fallback: Configuration Service downgraded classes 
@FeignClient (. Value = "Service-the Provide", fallback = ServiceProvideFallBack class )
 public  interface ServiceProvide {
 / **
* Call the service path does not pass parameters
* @return
*/
    @RequestMapping(value="/hello1",method = RequestMethod.GET)
String  hello1();
    /**
     * 
     * Pass a parameter
     * / 
    @ RequestMapping (value = "/ hello2", Method, = RequestMethod.GET)
     // @RequestParam which must write the parameter name, otherwise not read 
  String hello2 (@RequestParam ( "name" ) String name);
     / * *
     * Pass parameters object, and this requires Post request
     * @return
     */
    @RequestMapping(value="/hello3",method = RequestMethod.POST)
  String  hello3(@RequestBody User user);
}

 

   Class service degradation

package com.niugang.fallback;
import org.springframework.stereotype.Component;
import com.niugang.entity.User;
import com.niugang.service.ServiceProvide;
/**
 * 
 * Feign specified client service degradation class interface. fallback class must implement this Feign client annotation interface, and is an effective spring
 * Bean. (I.e., based on the added @component)
 *
 */
@Component
public class ServiceProvideFallBack implements ServiceProvide {
@Override
public String hello1() {
return "hello1 invoke fail";
}
@Override
public String hello2(String name) {
// TODO Auto-generated method stub
return "hello2 invoke fail";
}
@Override
public String hello3(User user) {
return "hello3 invoke fail";
}
}

 

 

   controller

package com.niugang.controller;


import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.niugang.entity.User;
import com.niugang.service.ServiceProvide;
@RestController
public class ComputeController {


private final Logger logger = org.slf4j.LoggerFactory.getLogger(ComputeController.class);


@Autowired
private ServiceProvide serviceProvide;
    /**
     * Invoked with no arguments
     * @return
     */
@RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
public String feign() {
logger.info("start invoke sevice provide");
return serviceProvide.hello1();
}


@RequestMapping(value = "/feign-consumer1/{name}", method = RequestMethod.GET)
public String feign1(@PathVariable String name) {
logger.info("start invoke sevice provide");
return serviceProvide.hello2(name);
}


@RequestMapping(value = "/feign-consumer2/{username}/{phone}", method = RequestMethod.GET)
public String feign2(@PathVariable String username, @PathVariable String phone) {
logger.info("start invoke sevice provide");
User user = new User();
user.setUsername(username);
user.setPhone(phone);
return serviceProvide.hello3(user);
}


}

 

 

test

Start the registry, start the service category, consumers start

It can be read from the log console print, but the thread sleep more than 2000ms, consumers will sense a second time to reconnect.

When stopped the service provider:

输入:http://localhost:9001/feign-consumer

Implementation of the corresponding service degradation function

输入:http://localhost:9001/feign-consumer1/zhangsan

Implementation of the corresponding service degradation function

                                                                               Micro-channel public number: 

                                               

                                                                             JAVA program ape growth path

                          Resource sharing, recording program ape growing little by little. Focus on Java, Spring, SpringBoot, SpringCloud, distributed, slightly services. 

Guess you like

Origin www.cnblogs.com/niugang0920/p/12193299.html