Spring Cloud个人学习

spring cloud Feign的使用(二)

2020-02-22  本文已影响0人  凌康ACG

前言

微服务开发需要用到服务间的调用Feign、也可以选择dubbo,但是dubbo上手有点难度,可参考另一篇文章https://www.jianshu.com/p/e11ff097424b
至于他们的优缺点,一个是rpc一个是http rest。Feign较带宽资源,对我们来说这点带宽还不是事,下面基于Feign来实现负载均衡和熔断,我们拿一个user的服务为例子。
基于上一篇的代码来做服务熔断:https://www.jianshu.com/p/7af37be1bedb
第一篇-使用:https://www.jianshu.com/p/7af37be1bedb
第二篇-熔断限流:https://www.jianshu.com/p/2945c88950d9
源码:https://github.com/xcocean/spring-cloud-feign-demo

技术栈

1、负载均衡:spring boot 2.1.x+nacos注册中心+Feign
2、熔断:sentinel+spring boot 2.1.x+nacos注册中心+Feign
关于spring boot的版本,我们先选择现在最新稳定的2.1.102020年2月22日
2.2.x可能有点坑,先不用它。

sentinel概述

Sentinel译为“哨兵”,顾名思义,面对您后台的大量服务/微服务,前置一个哨兵,但面对大量请求时,让后台服务有序被调用,但某些服务的不可用时,采用服务熔断降级等措施,让系统仍能平稳运行,不至于造成系统雪崩。应用场景可去github查看,我们在https://github.com/alibaba/Sentinel/tree/master/sentinel-dashboard可查看文档,直接去releases:https://github.com/alibaba/Sentinel/releases下载jar包https://github.com/alibaba/Sentinel/releases下载了一个目前最新的如何快速下载?打开梯子工具即可

image.png
然后用命令运行它:注意端口改成了 8888
java -Dserver.port=8888 -Dcsp.sentinel.dashboard.server=localhost:8888 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.7.1.jar

然后访问:http://localhost:8888 账号密码都是sentinel

一、user-feign熔断回调

接着在user-feign加入依赖:

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

application.yml内容改为如下:

spring:
  application:
    name: user-feign
  main:
    allow-bean-definition-overriding: true
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.112.1:8848   # 注意改成你的nacos地址
    sentinel:
      enabled: true
      transport:
        dashboard: 192.168.112.1:8888  # 注意改成你的地址和端口

feign:
  okhttp:
    enabled: true
  httpclient:
    enabled: false
  sentinel:
    enabled: true

创建一个失败回调UserServiceFeignFallback:

package com.qbccn.userfeign.feign.fallback;

import com.qbccn.userfeign.feign.UserServiceFeign;
import org.springframework.stereotype.Component;

@Component //交给spring托管
public class UserServiceFeignFallback implements UserServiceFeign {

    @Override
    public Object GetInfo() {
        return "触发熔断!";
    }
}
image.png
然后启动user-feign,其他的关闭,让他触发熔断返回固定结果
http://localhost:8080/user/info
image.png
上一篇下一篇

猜你喜欢

热点阅读