sprinboot系列九——微服務三——eureka客戶端使用feign

使用testboot這個項目
why?feign集成ribbon和hystrix,操作更加方便,傳參更便捷
使用testboot

pom

		<!-- SpringCloud 整合 Feign -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>

啓動類start.class新增註解

新增註解

@EnableFeignClients//調用者啓動時,打開Feign開關

ribbon類似代理功能

在onemiion工程
單服務中,具體實現如下:

	@ApiOperation(value = "獲取用戶列表", notes = "獲取用戶列表")
	@RequestMapping(value = "/hi2", method = RequestMethod.POST)
	@ResponseBody
	public String hi2(@RequestBody @ApiParam(value = "用戶數據") AppearIcon1 appear) {
		logger.info(new Gson().toJson(appear));
		return "hi, I'm springboot !"+Hello.hello;
	}

在testboot中,新增接口代理,指明代理的服務,以及方法對應的具體路徑和參數,與被代理的一致:

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import boot.dao.entity.AppearIcon1;


@FeignClient("one-million")
public interface FeignHelloService {
	@RequestMapping(value = "/one-million-dev/hi2", method = RequestMethod.POST)
	@ResponseBody
	public String hi2(@RequestBody  AppearIcon1 appear) ;
	
}

使用:

    //feig
    @Autowired
    private FeignHelloService feign;
    
	@RequestMapping(value = "/hi222", method = RequestMethod.POST)
	@ResponseBody
	public String hi2(@RequestBody  AppearIcon1 appear) {
		
		return feign.hi2(appear);
	}

項目啓動過後,輸入localhost:8092/test/hi222,加上相關請求體即可完成訪問

在這裏插入圖片描述

hystrix類似代理功能

0,打開feign開關,在application.yml中新增配置:

feign: 
   hystrix:
      enabled: true      

1,代理接口新增fallback類

@FeignClient(name="one-million",fallback=FeignHelloServiceBack.class)
public interface FeignHelloService {
	@RequestMapping(value = "/one-million-dev/hi2", method = RequestMethod.POST)
	@ResponseBody
	public String hi2(@RequestBody  AppearIcon1 appear) ;
	
}

2,新增FeignHelloServiceBack類,實現FeignHelloService 接口,實現的hi2接口的具體邏輯即爲fallback


@Component
public class FeignHelloServiceBack implements FeignHelloService{

	@Override
	public String hi2(AppearIcon1 appear) {
		return "back";
	}

}

關閉服務,或者修改FeignHelloService 中mapping的路徑即可得到返回:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章