- 在dubbo分布式服务框架中,控制层和业务层分开,使用的是org.apache.dubbo. … .的Reference注解注入业务层的对象。
- 在springcloud中无法使用Reference注解,所以使用feign实现
- 先添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 然后创建feign的接口,接口中写上服务提供者中的控制层方法,然后在消费者控制层直接注入feign的对象,就可以使用提供者的方法了
package com.offcn.feign;
import com.offcn.pojo.Movie;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "MOVIEPROVIDER01") //找到微服务的提供者
//@FeignClient(name = "MovieProvider01") //也可以使用name指向
public interface MovieFeign {
@GetMapping("/moviecontroller/getmovie/{id}")
public Movie getMovie(@PathVariable Integer id);
}
即feign的作用就是从消费者的微服务中指向了提供者的微服务
- 在消费者的主启动类上加上@EnableFeignClients的注解,允许feign
- 因为是远程调用,还传递了参数,所以需要在服务提供者的方法的参数传递上加上@PathVariable注解,在feign的接口中复制提供者方法的参数上也需要此注解,而且两者都需要在地址中加上{id}