Giter VIP home page Giter VIP logo

Comments (6)

kimmking avatar kimmking commented on August 28, 2024

good idea

from sentinel.

tigerMoon avatar tigerMoon commented on August 28, 2024

Here is my suggestion to integrate with Netflix Zuul:

Netflix Zuul just uses Servlet filters to chain the request. and has three stages pre route and post

just add CommonFilter in pre stage. it is the same to Sentinel Servlet Adapter.

the difference is the error handler. so just add another filter to trace error config in route and poststages like this:

Tracer.trace(e3);

if used in Spring Cloud family. Sentinel Spring Cloud Starter may be a good choice

from sentinel.

sczyh30 avatar sczyh30 commented on August 28, 2024

Hi, thanks for your suggestion. Here are some of my considerations:

  • Flow control for API gateway is different from web requests. Users often care about flow control for service (e.g. /serviceA/* pattern in API gateway), not for a specific URL.
  • Distributed flow control is often required for API gateway. This will be supported in later versions of Sentinel.
  • Zuul 2.x has breaking changes and is totally different from Zuul 1.x. Zuul 2.x leverages reactor pattern of Netty, so the implementation will be different (may depend on async support in Sentinel 0.2.0).

from sentinel.

zuonidelaowang avatar zuonidelaowang commented on August 28, 2024

zuul网关限流, 我们这边的实现方式, 欢迎大家交流沟通.


网关限流zuulFilter实现部分

public class AccessFilter extends ZuulFilter {
@OverRide
public String filterType() {
return FilterConstants.PRE_TYPE;
}

@Override
public int filterOrder() {
    return 1;
}

@Override
public boolean shouldFilter() {
    return true;
}

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
   // 统计API访问时间
    ctx.set("startTime", System.currentTimeMillis());
  // IP限流
    if (!sentinelIp(ctx)) {
        return null;
    }
  // 访问频率限流
    if (!sentinelApi(ctx)) {
        return null;
    }
    return null;
}

/**
 * @Author: ---
 * @Date: 2018/9/10 17:32
 * @Description: 限流IP
 **/
private boolean sentinelIp(RequestContext ctx) {
    HttpServletRequest request = ctx.getRequest();
    // 获取用户IP地址,将用户IP地址当做限流key
    String ip = IpTool.getIp(request);
    Entry entry = null;
    try {
        entry = SphU.entry(ip);
    } catch (BlockException e1) {
        log.info("API -> 限流ip:" + ip);
        // 过滤该请求,不往下级服务去转发请求,到此结束
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(429);
        ctx.setResponseBody("{\"result\":\"IP访问次数超限!\"}");
        ctx.getResponse().setContentType("application/json;charset=UTF-8");
        return false;
    } finally {
        if (entry != null) {
            entry.exit();
        }
    }
    return true;
}

/**
 * @Author: ---
 * @Date: 2018/9/10 17:32
 * @Description: 限流
 **/
private boolean sentinelApi(RequestContext ctx) {
    HttpServletRequest request = ctx.getRequest();
    //获取用户请求地址,将用户请求地址当做限流key
    String url = request.getServletPath();
    Entry entry = null;
    try {
        entry = SphU.entry(url);
    } catch (BlockException e1) {
        log.info("API -> api限流地址:" + url);
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(429);
        ctx.setResponseBody("{\"result\":\"API访问次数超限!\"}");
        ctx.getResponse().setContentType("application/json;charset=UTF-8");
        return false;
    } finally {
        if (entry != null) {
            entry.exit();
        }
    }
    return true;
}

}


网关限流规则

public class ZuulLimitInit {

@Resource(name = "redisTemplate")
private RedisTemplate redisTemplate;

/**
 * @Author: --------
 * @Date: 2018/9/11 13:15
 * @Description: 初始化限流规则
 **/
public void init() {
    // 从redis读取限流规则
    if (!RedisTool.exists(redisTemplate, ZuulLimitEnum.ZUUL_LIMIT.getKey())) {
        log.info("API -> 限流规则为空,直接返回");
        return;
    }
    // 把限流规则配置在redis
    List<String> list = RedisTool.hget(redisTemplate, ZuulLimitEnum.ZUUL_LIMIT.getKey());
    List<FlowRule> rules = new ArrayList<>();
    list.forEach(s -> {
        JSONObject jsonObject = JSONObject.parseObject(s);
        // 初始化限流规则
        FlowRule rule = new FlowRule();
        rule.setResource(jsonObject.getString("resource"));
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 每秒钟多少个QPS
        rule.setCount(jsonObject.getInteger("count"));
        rules.add(rule);
    });
    log.info("API -> 初始化限流规则:{}", rules);
    //加载限流规则
    FlowRuleManager.loadRules(rules);
}

}


启动项目后, 初始化限流规则

@EnableZuulProxy
@EnableDiscoveryClient
//@EnableFeignClients
@SpringBootApplication
public class CommonGatewayApplication implements CommandLineRunner {

@Autowired
private ZuulLimitInit zuulLimitInit;

public static void main(String[] args) {
    SpringApplication.run(CommonGatewayApplication.class, args);
}

@Override
public void run(String... strings) throws Exception {
    zuulLimitInit.init();
}

}

from sentinel.

tigerMoon avatar tigerMoon commented on August 28, 2024

Here give a sample for the integration of zuul1.
https://github.com/tigerMoon/sentinel-zuul-sample

And this video is good to know Zuul && Zuul2.
https://www.youtube.com/watch?v=2oXqbLhMS_A

from sentinel.

tigerMoon avatar tigerMoon commented on August 28, 2024

Finally. I know what does Zuul need. Zuul lack of rate limit or flow control what does Sentinel provide. We can give an adapter for Zuul. include Service API path and Authority features.

The user may use like this:

<dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>spring-cloud-zuul-sentinel-adapter</artifactId>
 </dependency>

// set property.
zuul.sentinel.enabled =true.

from sentinel.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.