一、新建module
cloud-consumer-feign-hystrix-order80
二、pom文件
<dependencies>
<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>otc.orientsec</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
三、建application.yml
server:
port: 80
spring:
application:
name: cloud-order-server
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka
四、主启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OpenFeignHystrixOrder80 {
public static void main(String[] args)
{
SpringApplication.run(OpenFeignHystrixOrder80.class,args);
}
}
当使用openfeign做客户端负载均衡时,需要两步
1. 主启动类加注解@EnableFeignClients
2. 创建service的接口,接口使用注解@FeignClient(value = "CLOUD-PAYMENT-SERVER")标注
其中value的值为注册中心的服务名。
五、创建业务类
5.1 openfeign的service接口
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVER")
public interface HystrixPaymentService {
@GetMapping("/payment/info/ok/{id}")
String paymentInfo_ok(@PathVariable("id") Integer id);
//模拟业务流程长,耗时长
@GetMapping("/payment/info/timeout/{id}")
String paymentInfo_timeout(@PathVariable("id") Integer id);
}
5.2 controller
@RestController
public class HystrixOrderController {
@Autowired
private HystrixPaymentService hystrixPaymentService;
@GetMapping("/consumer/payment/info/ok/{id}")
public String paymentInfo_ok(@PathVariable("id") Integer id)
{
return hystrixPaymentService.paymentInfo_ok(id);
}
//模拟业务流程长,耗时长
@GetMapping("/consumer/payment/info/timeout/{id}")
public String paymentInfo_timeout(@PathVariable("id") Integer id)
{
return hystrixPaymentService.paymentInfo_timeout(id);
}
}