Spring Cloud 服务消费者 Feign (三)

Feign

  Feign是一个声明式的Web服务客户端,使用Feign可使得Web服务客户端的写入更加方便。
它具有可插拔注释支持,包括Feign注解和JAX-RS注解、Feign还支持可插拔编码器和解码器、Spring Cloud增加了对Spring MVC注释的支持,并HttpMessageConverters在Spring Web中使用了默认使用的相同方式。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载平衡的http客户端。

新建Spring Boot 项目 

 

 

 pom 引包

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

修改配置文件

server.port=1004
spring.application.name=service-feigin
eureka.client.serviceUrl.defaultZone=http://地址/eureka/

 

  在启动主类添加注解

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ServicefeignApplication {

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

}
@EnableFeignClients 开启feign功能

新增一个接口
@FeignClient(name = "SERVICE-HI")
public interface IserviceFeign {
    @RequestMapping(value = "/hello/hi",method = RequestMethod.GET)
    String frignRequest(@RequestParam String name);
}

通过 @FeignClient(name = "SERVICE-HI") 指定要调用的服务 @RequestMapping(value = "/hello/hi",method = RequestMethod.GET) 指定服务提供的方法路径

新建控制器
@RestController
@RequestMapping("test")
public class HelloController {

    @Autowired
    private IserviceFeign iserviceFeign;

    @GetMapping("/hi")
    public String sayHi(@RequestParam String name) {
        return iserviceFeign.frignRequest( name );
    }
}

重复刷新请求链接http://localhost:1004/test/hi?name=aa  交替打印出

hi aa ,i am from port:1002

hi aa ,i am from port:1001



 

posted @ 2019-09-05 19:11  风吹一点云  阅读(262)  评论(0编辑  收藏  举报