本文共 2670 字,大约阅读时间需要 8 分钟。
Feign 整合了ribbon,具有负载均衡的能力;Feign 采用的是基于接口的注解
新建一个服务消费者模块consumer-feign,代码结构如下图所示。
4.0.0 com.cntaiping.tpa consumer-feign 0.0.1-SNAPSHOT jar consumer-feign Demo project for Spring Boot com.cntaiping.tpa cloud 1.0-SNAPSHOT org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-openfeign
eureka: client: serviceUrl: defaultZone: http://localhost:8800/eureka/server: port: 8500spring: application: name: consumer-feign
package com.cntaiping.tpa.consumerfeign;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication@EnableFeignClientspublic class ConsumerFeignApplication { public static void main(String[] args) { SpringApplication.run(ConsumerFeignApplication.class, args); }}
(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;@RestControllerpublic class MessageController { @Autowired SchedualService schedualService; @GetMapping(value = "/hello") public String hello(@RequestParam String name) { return schedualService.hello( name ); }}
转载地址:http://rgvab.baihongyu.com/