微服务之Feign远程调用
1.微服务之间一般都是业务分离,会创建一个独立的模块来存放接口,方便以后调用,以及防止代码的冗余和降低耦合性
2.导入feign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
3.构建feign模块,并创建接口
@FeignClient(value = "leadnews-wemedia")//服务调用者
public interface IWemediaClient {
/**
* 频道分类查询
* @return
*/
@GetMapping("/api/v1/channel/list")
public ResponseResult channel();
}
4.在leadnews-wemedia模块feign包下,创建一个实现类来实现远程接口,然后再对业务进行一个实现
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.wemedia.service.WmChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WemediaClient implements IWemediaClient {
@Autowired
private WmChannelService wmChannelService;
/**
* 查询所有频道分类
* @return
*/
@GetMapping("/api/v1/channel/list")
@Override
public ResponseResult channel() {
return wmChannelService.findAllChannel();
}
}
在leadnews-wemedia模块下也导入feign客户端依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
并在启动类上添加注解@EnableFeignClients(basePackages = “com.wcl.apis”),basePackages对应的是feign模块下接口的路径
5.测试,通过spring容器注入接口,进行一个调用
@Autowired
private IWemediaClient iWemediaClient;
@Test
public void test(){
ResponseResult channel = iWemediaClient.chanwnel();
}
注:不同的模块业务下都可以进行一个远程调用,但一定要导入feign客户端的依赖和启动类添加注解
@EnableFeignClients(basePackages = “com.wcl.apis”)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>