Feign使用了Ribbon的负载均衡功能,大大简化了远程调用时的代码
String url ="http://dept-provider/get?name="+name;
String forObject = template.getForObject(url, String.class);
1.使用feign改造consumer工程
1.引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.开启feign功能
@SpringBootApplication
@EnableFeignClients //开启feign客户端
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
3.删除RestTemplate
feign已经自动集成了Ribbon负载均衡的RestTemplate。所以,此处不需要再注册
RestTemplate。
4.创建Feign客户端 service层
package com.jd.service;
@FeignClient("address-provider")
public interface IAddressService {
@GetMapping("/address/list/{userId}")
List<Address> getByUserId(@PathVariable("userId") String userId);
}
5.修改consumer的controller
package com.jd;
@Controller
public class OrderController {
@Autowired
private IAddressService addressService;
@ResponseBody
@RequestMapping("/order/info.do")
public Map<String,Object> info(String userId) {
Map<String,Object> map = new HashMap<>();
map.put("addressList",addressService.getByUserId(userId));
map.put("goodsList",null);
return map;
}
}
6.在服务层做一下操作
配置文件更改
# 应用名称
spring.application.name=address-provider
# 应用服务 WEB 访问端口
server.port=7777
#指定Eureka注册中心访问地址
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:5555/eureka
#是否从Eureka注册中心抓取已有的注册消息,默认为true,单节点无所谓true或false,但是集群必须设置为true才能配合ribbon使用负载均衡
eureka.client.fetch-registry=true
controller层修改
package com.jd;
@Controller
public class AddressController {
@Autowired
private IAddressService addressService;
@ResponseBody
@GetMapping("/address/list/{userId}")
public List<Address> list(@PathVariable("userId") String userId) {
return addressService.getByUserId(userId);
}
}