目录
2.4在feign消费端修改启动类,新增相关注解 @EnableFeignClients和@ComponentScan
补充: feign集成了ribbon,默认使用轮询实现负载均衡
3.2 使用Ribbon + RestTemplate调用服务
1. 概述
feign是一个声明式的webservice客户端,使得编写服务客户端变得非常容易.
主要要创建一个接口,然后在上面添加注解即可.
2. feign使用步骤
2.1添加pom(消费端)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.2在公共api处新增
package com.jsp.springcloud.servicecloudapi.service;
import com.jsp.springcloud.servicecloudapi.model.Dept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@FeignClient(value = "SERVICECLOUD-DEPT")
public interface DeptClientService {
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/getAll", method = RequestMethod.GET)
List<Dept> getAll();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
boolean add(Dept dept);
}
2.3在feign消费端修改Controller
package com.jsp.springcloud.servicecloudconsumedeptfeign.controller;
import com.jsp.springcloud.servicecloudapi.model.Dept;
import com.jsp.springcloud.servicecloudapi.service.DeptClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class DeptController_Consumer {
@Autowired
private DeptClientService deptService;
@RequestMapping(value = "/dept/add")
public boolean add(Dept dept) {
return this.deptService.add(dept);
}
@RequestMapping(value = "/dept/get/{id}")
public Dept get(@PathVariable("id") Long id) {
return this.deptService.get(id);
}
@RequestMapping(value = "/dept/list")
public List<Dept> list() {
return this.deptService.getAll();
}
}
2.4在feign消费端修改启动类,新增相关注解 @EnableFeignClients和@ComponentScan
package com.jsp.springcloud.servicecloudconsumedeptfeign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.jsp.springcloud"})
@ComponentScan("com.jsp.springcloud")
public class ServicecloudConsumeDeptFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServicecloudConsumeDeptFeignApplication.class, args);
}
}
补充: feign集成了ribbon,默认使用轮询实现负载均衡
3. 消费服务端方式
3.1 feign 通过接口方式调用Rest服务
请求发送给Eureka服务器,通过Feign找到服务接口,服务调用时候融合了ribbon,所以支持负载均衡