Feign 整合了 Ribbon 与 Hystrix,同时还提供了一种声明式的 Webservice?客户端定义的方式。?
Springcloud 集成 Nacos注册中心
Provider?服务提供者
参考?Springcloud 集成 Nacos简单服务调用
Consumer 消费者
?pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
启动类
package com.lhy.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
// 开启Feign
@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
public class CloudApiApplication {
public static void main(String[] args) {
SpringApplication.run(CloudApiApplication.class, args);
}
}
本地Feign客户端
package com.lhy.cloud.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "user-api", path = "/user")
public interface UserClient {
@GetMapping("/headPortrait")
String headPortrait();
}
测试类
package com.lhy.cloud.controller;
import com.lhy.cloud.client.UserClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* Class description.
*
* @author ocean liu
* @createTime 2021/11/29 - 10:57
*/
@RequestMapping("/cloud")
@RestController
public class CloudController {
@Resource
private UserClient userClient;
@RequestMapping("/user/headPortrait")
public String getUserHeadPortrait() {
return userClient.headPortrait();
}
}
验证
负载均衡配置
pom.xml 配置负载策略
user-api:
ribbon:
# com.netflix.loadbalancer.RoundRobinRule 默认 轮询
# com.netflix.loadbalancer.RandomRule 随机
# com.netflix.loadbalancer.BestAvailableRule 最小并发
# com.netflix.loadbalancer.WeightedResponseTimeRule 响应时间 权重
# com.netflix.loadbalancer.ZoneAvoidanceRule 复合判读 区域性能也服务可用性
# com.netflix.loadbalancer.RetryRule 失败重试
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule
熔断配置
pom.xml 开启熔断器
feign:
hystrix:
enabled: true
重新编写本地Feign客户端,配置fallback
package com.lhy.cloud.client;
import com.lhy.cloud.client.fallback.UserClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "user-api", path = "/user", fallback = UserClientFallback.class)
public interface UserClient {
@GetMapping("/headPortrait")
String headPortrait();
}
编写fallback处理类
package com.lhy.cloud.client.fallback;
import com.lhy.cloud.client.UserClient;
import org.springframework.stereotype.Component;
/**
* Class description.
*
* @author ocean liu
* @createTime 2021/12/9 - 9:54
*/
@Component
public class UserClientFallback implements UserClient {
@Override
public String headPortrait() {
return "default.png";
}
}
测试关闭provider服务
测试开启provider服务
|