1、Feign简介
Feign 整合了ribbon,具有负载均衡的能力;Feign 采用的是基于接口的注解
2、新建模块
新建一个服务消费者模块consumer-feign,代码结构如下图所示。
2.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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cntaiping.tpa</groupId>
<artifactId>consumer-feign</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>consumer-feign</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>com.cntaiping.tpa</groupId>
<artifactId>cloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<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.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
2.2 配置文件application.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8800/eureka/
server:
port: 8500
spring:
application:
name: consumer-feign
2.3 启动类
package com.cntaiping.tpa.consumerfeign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class ConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerFeignApplication.class, args);
}
}
2.4 服务消费类
(1)Service层
定义一个feign接口,通过@ FeignClient(“服务名”),来指定消费哪个服务。
package com.cntaiping.tpa.consumerfeign.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "producer")
public interface SchedualService {
@RequestMapping(value = "/get",method = RequestMethod.GET)
String hello(@RequestParam(value = "name") String name);
}
(2)controller层
package com.cntaiping.tpa.consumerfeign.controller;
import com.cntaiping.tpa.consumerfeign.service.SchedualService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MessageController {
@Autowired
SchedualService schedualService;
@GetMapping(value = "/hello")
public String hello(@RequestParam String name) {
return schedualService.hello( name );
}
}