SpringCloud study notes 7 - SpringCloud declarative Feign client calls the tools, services avalanche effect

Source: Ants classroom video: http: //www.mayikt.com/course/video/2390

1, SpringCloud supports two client calls the tool:

   RestTemplate basically unused,

  Feign client tools use more, it is a statement of the http client calls the tool, using the interface + notes manner, readability strong.

  biggest advantage:

2, code implementation (based on the Eureka registry)

代码1:  pom.xml添加feign依赖,

<!-- feign客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>


代码2:在消费者中建立feign接口

/**
 * Feign书写方式以springmvc接口形式书写,
 * FeignClient调用服务接口,name就是服务名称
 * @author gh
 * 
 */
@FeignClient(name="app-member")
public interface ApiFeign {
	
	@RequestMapping("/getMember")
	public String getMember();

	/**
	 * 实现原理:通过反射机制,获取接口上的服务名称,然后去注册中心获取对应的实际地址,
	 * 再获取接口的调用方法,通过@RequestMapping获取到具体的url地址,
     * 然后在底层转化为rpc远程调用。
	 */
}



代码3:建立消费者调用controller

@RestController
public class FeignController {
	@Autowired
	private ApiFeign apiFeign;
	
	@RequestMapping("/feignGetMember")
	public String feignGetMember(){
		return apiFeign.getMember();
	}

}


代码4:启动类中加入注解
   (注意:如果@EnableFeignClients注解不加basePackages时,可能会导致启动时找不到feign接口,加或不加根据自己的包的位置来定。)

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages={"com.gonghua"})
public class AppOrder {
	public static void main(String[] args) {
		SpringApplication.run(AppOrder.class, args);
	}
}

Results are as follows:

3. Create Feign clients rely Project Cohesion

(1) the establishment of the parent project, maven of packaging types must be selected to war

The establishment of sub-projects (2) the parent project, this time to choose maven module

    

4, Service avalanche effect

       By default tomcat is only one all service requests thread pool to handle the client sent, so, in a highly concurrent, if all of the client's request accumulate to the same service interface, it will have all the threads of tomcat to deal with the service interface, the interface could lead to other services inaccessible. It will cause the interface to access other services when a delay and wait.

5, Feign client timeout configuration

springcloud feign client's default timeout is 1 second, in order to solve this problem, we can make the following configurations:

     application.properties configuration inside: (springcloud feign client default on support ribbon)

##设置feign客户端超时时间: 
##指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ribbon.ReadTimeout: 5000
##指的是建立连接后从服务器读取到可用资源所用的时间
ribbon.ConnectTimeout=5000

 

Published 27 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/gonghua0502/article/details/103270842