SpringCloud學習筆記(三)feign———服務消費者
阿新 • • 發佈:2019-01-31
上篇講到了服務消費者ribbon ,這篇我記錄另一種服務消費者feign
簡而言之 feign採用的是基於介面的註解 使用很方便 並且整合了ribbon
繼續用我們之前的工程,啟動serv 並且啟動兩個客戶端,詳情請看上篇有詳細記錄如何啟動一個serv (8761) 兩個client(8762、8763)
首先建立feign的工程,還是一個全新的springboot工程,
需要依賴
web
eureka
feign
建立好之後 進行配置 向註冊中心註冊
這裡要多加一個@EnableFeignClients註解 表明我們要是使用feign消費服務啦~
package com.chunying.feign; importorg.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; @EnableDiscoveryClient @EnableFeignClients @SpringBootApplicationpublic class FeignApplication { public static void main(String[] args) { SpringApplication.run(FeignApplication.class, args); } }
application.properties配置 和以前的相同
server.port=8765 eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ spring.application.name=service_feign
埠8765 服務名service_feign
接下來寫測試類service,注意feign是基於介面的,所以要建立一個interface
註解@FeignClient(value="服務名") 表明要呼叫哪個服務
方法是呼叫服務中的具體哪個介面,包括引數等
package com.chunying.feign.service; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * @author chunying */ @FeignClient(value = "hello") public interface HelloService { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String helloFromClient(@RequestParam(value="name") String name); }
然後寫一個controller 呼叫我們的service
package com.chunying.feign.Controller; import com.chunying.feign.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author chunying */ @RestController public class HelloController { @Autowired private HelloService helloService; @RequestMapping(value = "/hello" , method = RequestMethod.GET) public String hello(@RequestParam String name) { return helloService.helloFromClient(name); } }
是不是很簡單呢,啟動工程
頁面出現證明註冊成功啦
訪問http://localhost:8765/hello?name=ying
交替出現結果
hello!8762,ying,come here
hello!8763,ying,come here
證明成功了,其實和ribbon是差不多的 只是實現方式是基於介面的了 ,寫起來更方便了
兩種服務消費者就記錄完畢了~~歡迎討論學習