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客戶端。java

新建Spring Boot 項目 

 

 

 pom 引包web

   <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>

修改配置文件spring

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

 

  在啓動主類添加註解app

@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) 指定服務提供的方法路徑spring-boot

新建控制器
@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:1002spa

hi aa ,i am from port:1001code

相關文章
相關標籤/搜索