1. pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-demo</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>feign-consumer</artifactId>
<packaging>jar</packaging>
<name>feign-consumer</name>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
2. FeignConsumerApplication 启动类
package com.imooc.springcloud;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* Created by 半仙.
*/
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class FeignConsumerApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(FeignConsumerApplication.class)
.web(WebApplicationType.SERVLET)
.run(args);
}
}
3. IService接口类
通过这个类来发起远程调用
- @FeignClient("eureka-client")
- @GetMapping("/sayHi")
package com.imooc.springcloud;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Created by 半仙.
*/
@FeignClient("eureka-client")
public interface IService {
@GetMapping("/sayHi")
String sayHi();
}
4. Controller类
package com.imooc.springcloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by 半仙.
*/
@RestController
public class Controller {
@Autowired
private IService service;
@GetMapping("/sayHi")
public String sayHi() {
return service.sayHi();
}
}
5. application.properties配置文件
spring.application.name=feign-consumer
server.port=40001
eureka.client.serviceUrl.defaultZone=http://localhost:20000/eureka/
# 每台机器最大重试次数
feign-client.ribbon.MaxAutoRetries=2
# 可以再重试几台机器
feign-client.ribbon.MaxAutoRetriesNextServer=2
# 连接超时
feign-client.ribbon.ConnectTimeout=1000
# 业务处理超时
feign-client.ribbon.ReadTimeout=2000
# 在所有HTTP Method进行重试
feign-client.ribbon.OkToRetryOnAllOperations=true
网友评论