Eureka注册中心:《使用IntelliJ IDEA创建Spring Cloud服务注册中心》
服务提供者创建:《使用IntelliJ IDEA创建Spring Cloud的Eureka Client》
Ribbon实现负载均衡:《使用IntelliJ IDEA创建Ribbon项目实现负载均衡》
File---new---module---Spring Assistant
单击next,进入如下图页面
点击next,在如下图页面中勾选Spring Cloud Discovery、Eureka Server
点击next
点击finish,完成项目创建。
在上图中的resources目录下新建application.yml,application.yml的功能和application.properties是一样的,但yml文件是树状结构,有更好的层次感,更易于理解。然后,删除原有的application.properties。如下图
修改其内容如下,其中name为注册到注册中心的服务名,可以自定义。
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8100
spring:
application:
name: acyx-feign
配置项目
参考Feign官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/3.0.0.M1/reference/html/
项目中如何集成Feign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
等待对应的依赖包下载完毕后,就不会为红色字体了,如下图
AcyxfeignApplication.java
package com.acyx.feign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class AcyxfeignApplication {
public static void main(String[] args) {
SpringApplication.run(AcyxfeignApplication.class, args);
}
}
查看官网文档
如下图箭头所指示内容为该feign代理访问的stores服务提供的具体接口
在acyxfeign项目中添加相关代码
HomeFeignService.java
package com.acyx.feign.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "acyx-stock")
public interface HomeFeignService {
@RequestMapping(value = "/home")
String homeFeign(@RequestParam(value = "name") String name);
}
HomeFeignController.java
package com.acyx.feign.controller;
import com.acyx.feign.service.HomeFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeFeignController {
@Autowired
private HomeFeignService homeFeignService;
@RequestMapping("/homeFeign")
public String homeFeign(String name){
return homeFeignService.homeFeign(name);
}
}
依次启动Eureka注册中心、acyxstock、acyxstocktwo、acyxfeign,然后在浏览器中访问:http://127.0.0.1:8761
在浏览器中访问:http://localhost:8100/homeFeign?name=Feign
刷新
再次刷新
因此,Feign在简化网络连接的同时,还使用了Ribbon负载均衡的功能。
欢迎关注个人微信公众号“我爱编程持之以恒”