第三步:新建StockFeignServicespringcloudalibaba com.example 0.0.1-SNAPSHOT 4.0.0 order-openfeign org.springframework.boot spring-boot-starter-web com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery org.springframework.cloud spring-cloud-starter-openfeign
package com.example.order.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "stock-service",path = "/stock")
public interface StockFeignService {
@RequestMapping("/reduck")
String reduck();
}
第四步:修改OrderApplication
删除不用的restTemplate和添加启动openFeign组件
package com.example.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableFeignClients //启动openFeign组件
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
}
第五步:修改OrderController
package com.example.order.controller;
import com.example.order.feign.StockFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private StockFeignService stockFeignService;
@RequestMapping("/add")
public String add(){
System.out.println("下单成功");
String msg = stockFeignService.reduck();
return "Hello World " + msg;
}
}
第六步:修改application.yml
server:
port: 8086
#应用名称(nacos会将该名称当做服务名称)
spring:
application:
name: order-service
cloud:
nacos:
server-addr: 127.0.0.1:8848
discovery:
username: nacos
password: nacos
namespace: public
第七步:启动服务测试
访问:http://localhost:8086/order/add
feign这种远程调用方式它也会自动的帮我们集成ribbon,集成负载均衡器,同样的也会帮我们集成nacos,会根据我@FeignClient(name = “stock-service”,path = “/stock”)注解的name中的服务名去nacos中获取对应的所有的实例,然后在结合负载均衡器来进行调用,feign使用了动态代理。



