(三)spring-cloud入门学习:服务消费Feign

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。

1. 创建一个名为eureka_feign的工程,pom.xml


  4.0.0

  com.kevin
  eureka_ribbon
  0.0.1-SNAPSHOT
  jar

  eureka_ribbon
  http://maven.apache.org

  
    UTF-8
  

  
    org.springframework.boot
    spring-boot-starter-parent
    2.1.4.RELEASE
  

  
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
    
    
        org.springframework.cloud
        spring-cloud-starter-openfeign
    
    
        org.springframework.boot
        spring-boot-starter-actuator
    
  
  
  
    
        
           org.springframework.cloud
           spring-cloud-dependencies
           Greenwich.SR1
           pom
           import
        
    
  

2. application.properties

spring.application.name=eurekaFeign
server.port=9202

eureka.client.serviceUrl.defaultZone=http://localhost:9101/eureka/
eureka.client.healthcheck.enabled=true

3. Application.java,启用Feign

package com.kevin.eureka_feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Application {
	
    public static void main( String[] args ) {
    	SpringApplication.run(Application.class, args);
    }
}

4. 使用feign申明service接口,HelloService.java

package com.kevin.eureka_feign.service;

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

@FeignClient("eurekaClient")
public interface HelloService {

	@RequestMapping("/sayHello")
	String sayHello();

}

5. 对外开放接口

package com.kevin.eureka_feign.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kevin.eureka_feign.service.HelloService;

@RestController
public class HelloController {
	
	@Autowired
	private HelloService helloService;
	
	@RequestMapping("sayHello")
	public String sayHello() {
		return helloService.sayHello();
	}
	
}

6. 启动测试http://127.0.0.1:9202/sayHello
(三)spring-cloud入门学习:服务消费Feign_第1张图片

在这里插入图片描述

你可能感兴趣的:(spring-cloud,Feign,spring-cloud,微服务,服务消费,Spring,Cloud)