<?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>com.imooc</groupId>
<version>1.0.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>
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
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);
}
}
@EnableDiscoveryClient 表示开启服务发现
@EnableFeignClients 表示开启Feign
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();
}
创建一个接口,并在上面写上@FeignClient(“eureka-client”)注解即可,然后写相应的方法,就可以访问到该服务的接口啦
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();
}
}
将接口注入,像在本地使用一样调用即可