Feign与Ribbon的区别在于,Ribbon使用微服务名来访问,利用RestTemplate对Http请求封装处理,而Feign在此基础上进一步封装,使用接口和注解,这会使Http客户端的编写更容易。Feign相较Ribbon可读性提高,但性能降低
项目结构
导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.3</version>
</dependency>
Service接口,开启注解@FeignClient
@FeignClient(value = "http://SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
@GetMapping("/dept/get/{id}")
public Dept queryById(@PathVariable("id") Long id);
@GetMapping("/dept/list")
public List<Dept> queryAll();
@PostMapping("/dept/add")
public boolean addDept(Dept dept);
}
项目结构
配置文件
server:
port: 80
spring:
application:
name: SPRINGCLOUD-CONSUMER-DEPT
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
register-with-eureka: false #不注册到eureka中
instance:
instance-id: springcloud-consumer-dept80 #描述信息
prefer-ip-address: true #优先使用ip注册,访问显示ip
management:
endpoints:
web:
exposure:
include: "*"
info:
env:
enabled: true
# 暴露端点info
info:
app.name: yl-springcloud
company.name: www.yl.com
build.artifactId: com.yl.springcloud
build.version: 1.0-SNAPSHOT
Controller
@RestController
public class DeptConsumerController {
//消费者没有service
//RestTemplate 直接调用 注册到spring
//(URL,实体 Map, Class<T>, responseType)
@Autowired
private DeptClientService service = null;
@GetMapping("/consumer/dept/get/{id}")
public Dept queryById(@PathVariable("id") Long id){
return this.service.queryById(id);
}
@GetMapping("/consumer/dept/list")
public List<Dept> queryAll(){
return this.service.queryAll();
}
@PostMapping("/consumer/dept/add")
public boolean addDept(Dept dept){
return this.service.addDept(dept);
}
}
主启动类,开启注解@EnableFeignClients
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.yl.springcloud"})
public class FeignDeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(FeignDeptConsumer_80.class,args);
}
}