SpringCloud---SpringCloud Feign(一)

Feign简述:

         消费者可以通过SpringCloud微服务的Feign组件技术去调用Eureka中的微服务实例,实现传统的面向接口编程。

创建消费者module:

        pom.xml加入web坐标  Eureka客户端坐标  Feign坐标

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

         application.properties配置Eureka地址和微服务实例应用名称

server.port=8081

#此module不进行注册
eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

#自定义配置
#要消费的微服务实例的应用名称
provided_url=SERVICE

         Service层,使用Feign调用微服务实例

/**
 * DESC :  通过Fegin调用微服务实例,实现传统的面向接口编程
 * @author Lonely
 *
 */
@FeignClient(value = "${provided_url}")  //Eureka注册中心的微服务实例应用名称
public interface TestService {

	//对应微服务实例中的接口路径
	@RequestMapping(value="/testcontroller.do/{id}/{name}",method=RequestMethod.GET)
	public String testController(@PathVariable("id") int id,@PathVariable("name") String name);

}

         Controller层调用Service层

@Controller
public class TestController {
	
	
	@Autowired
	private TestService testService;     //调用Service层
	
	@RequestMapping(value="/testConsume.do/{id}/{name}",method=RequestMethod.GET)
	@ResponseBody
	public String test(@PathVariable("id") int id,@PathVariable("name") String name) {
		return testService.testController(id, name);
	}
	
}

        启动类,添加Feign扫描注解 Eureka客户端注解 

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = "online.liema.service") //扫描使用 @FeignClient 注解的Service层
public class FeignApp {
	public static void main(String[] args) {
		SpringApplication.run(FeignApp.class, args);
	}
}

先依次启动三个Eureka,再依次启动微服务实例,最后启动Feign module,访问Controller。Feign会进行负载均衡,默认使用的轮询算法。

发布了72 篇原创文章 · 获赞 31 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_39115469/article/details/104696031