Spring Cloud Feign 실례 설명 학습
Feign 은 Ribbon 과 Hystrix 를 포함 하고 있 습 니 다.이것 은 실전 에서 그 의 미 를 천천히 느 낄 수 있 습 니 다.이른바 Feign 의 jar 가방 은 Ribbon 과 Hystrix 의 jar 가방 이라는 물리 적 인 포함 이 아니 라 Feign 의 기능 은 다른 두 가지 기능 이라는 논리 적 인 가방 을 포함 하고 있 습 니 다.즉,Feign 은 Ribbon 과 Hystrix 의 일 을 할 수 있 지만 Ribbon 과 Hystrix 가 가지 고 있 는 주 해 를 사용 하려 면 해당 하 는 jar 가방 을 도입 해 야 한다.
사례 1:
Eureka 등록 센터:https://github.com/yejingtao/forblog/tree/master/demo-eureka-register
서비스 제공 자:https://github.com/yejingtao/forblog/tree/master/demo-feign-freeservice
서비스 호출 자:https://github.com/yejingtao/forblog/tree/master/demo-feign-freeconsumer
서비스 제공 자 는 간단 한 Eureka Client 엔 드+웹 응용 프로그램 으로 다음 과 같은 방법 을 제공 합 니 다.
@RestController 
@RequestMapping("/feign-service") 
public class HelloServiceContorller { 
  private Logger logger = LoggerFactory.getLogger(this.getClass());    
  private void sleep(String methodName) { 
    int sleepMinTime = new Random().nextInt(3000); 
    logger.info("helloService "+methodName+" sleepMinTime: "+sleepMinTime); 
    try { 
      Thread.sleep(sleepMinTime); 
    } catch (InterruptedException e) { 
      e.printStackTrace(); 
    } 
  } 
   
  @RequestMapping(value="/serviceGet",method=RequestMethod.GET) 
  public String helloService(@RequestParam String name) { 
    sleep("get"); 
    return "HelloServiceImpl name :"+name; 
  } 
   
  @RequestMapping(value="/serviceHead", method=RequestMethod.HEAD) 
  public String helloService(@RequestHeader String name, 
      @RequestHeader String password) { 
    sleep("header"); 
    return "helloServiceHead name :"+name +" password:"+password; 
  } 
   
  @RequestMapping(value="/servicePost", method=RequestMethod.POST) 
  public String helloService(@RequestBody UserDemo userDemo) { 
    sleep("post"); 
    return userDemo.toString(); 
  } 
} @RequestParam:Annotation which indicates that amethod parameter should be bound to a web request parameter
@RequestBody:Annotation indicating a methodparameter should be bound to the body of the web request.
@RequestHeader:Annotation which indicates that amethod parameter should be bound to a web request header.
상기 주석 이 부족 하면 서비스 가 실 행 된 후에 잘못 보고 되 지 는 않 지만 입 참 을 얻 지 못 합 니 다.
서비스 호출 자 항목:
<dependency> 
      <groupId>org.springframework.cloud</groupId> 
      <artifactId>spring-cloud-starter-feign</artifactId> 
    </dependency> 
application.yml:
server: 
 port: 9051 
 
spring: 
 application: 
  name: demo-feign-freeconsumer 
   
eureka: 
 client: 
  serviceUrl: 
   defaultZone: http://peer1:1111/eureka/,http://peer2:1112/eureka/ 
feign: 
 hystrix: 
  enabled: true 
 
#Ribbon        
#ribbon: 
# ConnectTimeout: 500 
# ReadTimeout: 3000응용 프로그램 시작 프로그램
@SpringBootApplication 
@EnableEurekaClient 
@EnableFeignClients 
public class DemoFeignApplication {    
  public static void main(String[] args) { 
    SpringApplication.run(DemoFeignApplication.class, args); 
  } 
}핵심 클 라 이언 트 코드
@FeignClient(name="demo-feign-freeservice",fallback=DemoFeignFallback.class) 
public interface DemoFeignService{ 
    
  @RequestMapping(value="/feign-service/serviceGet",method=RequestMethod.GET) 
  String helloService(@RequestParam("name") String name); 
   
  @RequestMapping(value="/feign-service/serviceHead", method=RequestMethod.HEAD) 
  String helloService(@RequestHeader("name") String name, 
      @RequestHeader("password") String password); 
   
  @RequestMapping(value="/feign-service/servicePost", method=RequestMethod.POST) 
  String helloService(@RequestBody UserDemo userDemo);  
} @RequestMapping 에 서 는 요청 의 상대 url 과 http 요청 방식 을 지정 하여 서버 와 일일이 대응 합 니 다.인삼 에 들 어간@RequestParam,
@RequestBody,@RequestHeader 주 해 는 서버 보다 value 속성 이 많 습 니 다.여 기 는 생략 할 수 없습니다.Feign 클 라 이언 트 인자 가 어떻게 대응 하 는 지 명시 적 으로 알려 야 합 니 다.
강등 서비스 코드:
@Component 
public class DemoFeignFallback implements DemoFeignService{ 
  @Override 
  public String helloService(String name) { 
    return "get error"; 
  } 
 
  @Override 
  public String helloService(String name,String password) { 
    return "head error"; 
  } 
   
  @Override 
  public String helloService(UserDemo userDemo) { 
    return "post error"; 
  } 
} 컨트롤 러 코드:
@RestController 
public class DemoFeignController {    
  @Autowired 
  private DemoFeignService demoFeignService;    
  @RequestMapping(value="/test", method=RequestMethod.GET) 
  public String demoServiceTest() { 
    StringBuffer sb = new StringBuffer(); 
    sb.append(demoFeignService.helloService("yuanyuan")); 
    sb.append("
"); 
    sb.append(demoFeignService.helloService("yjt","xixihaha")); 
    sb.append("
"); 
    sb.append(demoFeignService.helloService(new UserDemo("yejingtao","123456"))); 
    return sb.toString();      
  } 
}  
  
 Google 서 비 스 는 시간 을 초과 하지 않 았 습 니 다.세 가지 방법 이 모두 정상 이지 만 head 요청 은 반환 값 을 받 지 못 했 습 니 다.이것 은 head 방식 http 요청 의 특성 에 의 해 결정 되 었 습 니 다.head 는 response 의 body 체 를 되 돌려 주지 않 고 연결 성 테스트 를 하 는 데 사 용 됩 니 다.
한 조 더 보기:
운 이 나 빠 head 와 post 요청 방법 처리 시간 이 2000 ms 를 넘 었 고 서비스 가 강등 되 어 fallback 처리 류 로 대체 되 었 습 니 다.
 
  
 사례 1 에서 우 리 는 서비스 제공 자 와 서비스 호출 자가 중복 되 는 코드 가 존재 하 는데 최적화 할 수 있 습 니까?사례 2 를 보십시오.
사례 2:
Eureka 등록 센터:https://github.com/yejingtao/forblog/tree/master/demo-eureka-register
인터페이스 API:https://github.com/yejingtao/forblog/tree/master/demo-feign-serviceapi
서비스 제공 자:https://github.com/yejingtao/forblog/tree/master/demo-feign-serviceimpl
서비스 호출 자:https://github.com/yejingtao/forblog/tree/master/demo-feign-apiconsumer
사례 2 의 가장 큰 변동 은 서비스 능력 을 하나의 API 프로젝트 에 단독으로 쓰 는 것 이다.호출 자 와 제공 자 pom 은 모두 이 API 에 의존한다.
API:
public interface HelloService {    
  @RequestMapping(value="/feign-service/serviceGet",method=RequestMethod.GET) 
  String helloService(@RequestParam("name") String name); 
   
  @RequestMapping(value="/feign-service/serviceHead", method=RequestMethod.HEAD) 
  String helloService(@RequestHeader("name") String name, 
      @RequestHeader("password") String password); 
   
  @RequestMapping(value="/feign-service/servicePost", method=RequestMethod.POST) 
  String helloService(@RequestBody UserDemo userDemo);    
} 
@RestController 
public class HelloServiceContorller implements HelloService{    
  private Logger logger = LoggerFactory.getLogger(this.getClass());    
  private void sleep(String methodName) { 
    int sleepMinTime = new Random().nextInt(3000); 
    logger.info("helloService "+methodName+" sleepMinTime: "+sleepMinTime); 
    try { 
      Thread.sleep(sleepMinTime); 
    } catch (InterruptedException e) { 
      e.printStackTrace(); 
    } 
  } 
   
  @Override 
  public String helloService(@RequestParam("name") String name) { 
    sleep("get"); 
    return "HelloServiceImpl name :"+name; 
  } 
   
  @Override 
  public String helloService(@RequestHeader("name") String name, 
      @RequestHeader("password") String password) { 
    sleep("header"); 
    return "helloServiceHead name :"+name +" password:"+password; 
  } 
   
  @Override 
  public String helloService(@RequestBody UserDemo userDemo) { 
    sleep("post"); 
    return userDemo.toString(); 
  }       
} 
@FeignClient(name="demo-feign-serviceimpl", fallback=FeignServiceFallback.class) 
public interface FeignService extends HelloService{  
} 두 가지 스타일 은 각각 장단 점 이 있다.freestyle 의 더욱 자 유 롭 고 서버 의 새로운 방법 은 클 라 이언 트 코드 에 영향 을 주지 않 는 다.단점 은 서비스 능력 이 동기 화 되 지 않 으 면 서비스 능력 의 변동 이 이상 을 일 으 킬 수 있다 는 것 이다.API 형식 서버 의 클 라 이언 트 서비스 능력 은 동기 화 되 지만 인터페이스의 변동 은 양쪽 코드 를 수정 해 야 하 며 구축 이 필요 할 때 잘 고려 해 야 합 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.