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);
    }

}
相关文章
相关标签/搜索