准备工作:四个项目,1个eureka-server、2个eureka-client、1个eureka-client2、feign-client
eureka-server:服务注册中心
eureka-client、eureka-client2:服务提供者
feign-client:服务消费者
server、client可以参考上一篇进行编写
https://blog.csdn.net/mzjmmc/article/details/108711676
这里要注意:两个client,端口不一样,但是应用名称是一样的,其余重复的代码,不多讲。这里着重讲用feign实现服务消费者
server.port=8762
spring.application.name=springcloud-client
server.port=8764
spring.application.name=springcloud-client
(1)application类,同时注册为controller(虽然同时注册为controller会违反MVC模式,但是为了看起来简便,就直接注册为controller)
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@RestController
public class TestSpringCloudFeignApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringCloudFeignApplication.class, args);
}
@Autowired
private MyFeignClient feignClient;
@GetMapping(value = "/hello")
public String sayHi(@RequestParam String name) {
String result = this.feignClient.sayHiFromClientOne(name);
return result;
}
}
2.编写feign接口
package com.example.demo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "springcloud-client")
public interface MyFeignClient {
@RequestMapping(value = "/hi", method = RequestMethod.GET)
String sayHiFromClientOne(@RequestParam(value = "name") String name);
}
3.application.properties
eureka.client.service-url.defaultZone= http://localhost:8761/eureka/
eureka.client.fetch-registry=true
server.port=8763
spring.application.name=test-feign
4.测试
打开http://localhost:8761/,发现server有了三个服务
打开localhost:8763/hello?name=mzj,并刷新多次,发现有两种结果
hi mzj,i am from port:8764
hi mzj,i am from port:8762
说明系统已实现负载均衡的功能,8764端口和8762端口都能获取服务,服务注册中心(eureka-server)会根据实际情况,选择不同的服务提供者(eureka-client)来为服务消费者(feign-client)提供服务