spring cloud 建一個服務消費者client-feign(最好用這種方式)

Feign是一個聲明式的僞Http客戶端,它使得寫Http客戶端變得更簡單。使用Feign,只須要建立一個接口並註解。它具備可插拔的註解特性,可以使用Feign 註解和JAX-RS註解。Feign默認集成了Ribbon,並和Eureka結合,默認實現了負載均衡的效果web

簡而言之:spring

  • Feign 採用的是基於接口的註解
  • Feign 整合了ribbon

新建一個spring-boot工程,取名爲serice-feign,在它的pom文件引入Feign的起步依賴spring-cloud-starter-feign、Eureka的起步依賴spring-cloud-starter-eureka、Web的起步依賴spring-boot-starter-webapp

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
server.port=8765
spring.application.name=client-feign
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ClientfeignApplication {

   public static void main(String[] args) {
      SpringApplication.run(ClientfeignApplication.class, args);
   }
}

 

定義一個feign接口,經過@ FeignClient(「服務名」),來指定調用哪一個服務。好比在代碼中調用了service-hi服務的「/hi」接口,代碼以下:負載均衡

@FeignClient(value = "service-hi")
public interface SchedualServiceHi {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}

定義controllerspring-boot

@RestController
public class HiController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SchedualServiceHi schedualServiceHi;

    @RequestMapping(value = "/hi")
    public String sayHi(@RequestParam String name){
        logger.info("feign ====> "+name);
        return schedualServiceHi.sayHiFromClientOne(name);
    }

}
相關文章
相關標籤/搜索