1 创建springboot项目,引入jar依赖
<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"> <modelVersion>4.0.0</modelVersion> <groupId>com.beifeng.hadoop</groupId> <artifactId>beifeng-spring-cloud-consumer-feign</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>beifeng-spring-cloud-consumer-feign</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 声明为web项目 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 配置eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- 配置feign依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.RC1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project>
2 配置相关配置
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/ #注册服务器地址
server:
port: 8765
spring:
application:
name: cloud-consumer-feign
3 调用服务接口
@FeignClient("service-hi")//指定调用哪个服务提供者 public interface IHiService { @RequestMapping(value="/info",method=RequestMethod.GET)//指定调用服务提供者的哪个接口 String info(); }
4 在启动类中声明使用feign
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients//启用feign @RestController public class ConsumerFeign { private static final Logger logger = LoggerFactory.getLogger(ConsumerFeign.class); @Autowired IHiService hiService; @RequestMapping("info") public String info() { String response=hiService.info(); logger.info(response); return response; } public static void main(String[] args) { SpringApplication.run(ConsumerFeign.class, args); } }
5 启用查看结果
feign内置了ribbon,自动实现负载均衡