com.alibaba.csp.sentinel.Entry Java Examples

The following examples show how to use com.alibaba.csp.sentinel.Entry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClusterFlowClientController.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 模拟流量请求该方法
 */
@GetMapping("/clusterFlow")
public @ResponseBody
String clusterFlow() {
    Entry entry = null;
    String retVal;
    try{
        entry = SphU.entry(RESOURCE_NAME, EntryType.IN,1);
        retVal = "passed";
    }catch(BlockException e){
        retVal = "blocked";
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return retVal;
}
 
Example #2
Source File: WarmUpFlowDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #3
Source File: WarmUpFlowDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            // token acquired, means pass
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(2000));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #4
Source File: WarmUpRateLimiterFlowDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            // token acquired, means pass
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(2000));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #5
Source File: WarmUpRateLimiterFlowDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #6
Source File: DemoController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/link")
@ResponseBody
public String link() throws BlockException {

    Entry entry = SphU.entry("head1", EntryType.IN);

    Entry entry1 = SphU.entry("head2", EntryType.IN);
    Entry entry2 = SphU.entry("head3", EntryType.IN);
    Entry entry3 = SphU.entry("head4", EntryType.IN);

    entry3.exit();
    entry2.exit();
    entry1.exit();
    entry.exit();
    return "successfully create a call link";
}
 
Example #7
Source File: PullConsumerDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void doSomething(MessageExt message) {
    pool.submit(() -> {
        Entry entry = null;
        try {
            ContextUtil.enter(KEY);
            entry = SphU.entry(KEY, EntryType.OUT);

            // Your business logic here.
            System.out.printf("[%d][%s][Success: %d] Receive New Messages: %s %n", System.currentTimeMillis(),
                Thread.currentThread().getName(), SUCCESS_COUNT.addAndGet(1), new String(message.getBody()));
        } catch (BlockException ex) {
            // Blocked.
            System.out.println("Blocked: " + FAIL_COUNT.addAndGet(1));
        } finally {
            if (entry != null) {
                entry.exit();
            }
            ContextUtil.exit();
        }
    });
}
 
Example #8
Source File: FlowPartialIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowRule_other() {

    FlowRule flowRule = new FlowRule();
    flowRule.setResource("testOther");
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(0);
    flowRule.setLimitApp("other");
    FlowRuleManager.loadRules(Arrays.asList(flowRule));

    Entry e = null;
    try {
        e = SphU.entry("testOther");
    } catch (BlockException e1) {
        e1.printStackTrace();fail("Should had failed");
    }

    if (e != null) {
        e.exit();
    } else {
        fail("Should had failed");
    }
}
 
Example #9
Source File: ParamFlowQpsRunner.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

    while (!stop) {
        Entry entry = null;
        T param = generateParam();
        try {
            entry = SphU.entry(resourceName, EntryType.IN, 1, param);
            // Add pass for parameter.
            passFor(param);
        } catch (BlockException e) {
            // block.incrementAndGet();
            blockFor(param);
        } catch (Exception ex) {
            // biz exception
            ex.printStackTrace();
        } finally {
            // total.incrementAndGet();
            if (entry != null) {
                entry.exit(1, param);
            }
        }

        sleep(ThreadLocalRandom.current().nextInt(0, 10));
    }
}
 
Example #10
Source File: MetricExitCallbackTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void onExit() {
    FakeMetricExtension extension = new FakeMetricExtension();
    MetricExtensionProvider.addMetricExtension(extension);

    MetricExitCallback exitCallback = new MetricExitCallback();
    StringResourceWrapper resourceWrapper = new StringResourceWrapper("resource", EntryType.OUT);
    int count = 2;
    Object[] args = {"args1", "args2"};
    extension.rt = 20;
    extension.success = 6;
    extension.thread = 10;
    Context context = mock(Context.class);
    Entry entry = mock(Entry.class);
    when(entry.getError()).thenReturn(null);
    when(entry.getCreateTime()).thenReturn(TimeUtil.currentTimeMillis() - 100);
    when(context.getCurEntry()).thenReturn(entry);
    exitCallback.onExit(context, resourceWrapper, count, args);
    Assert.assertEquals(120, extension.rt, 10);
    Assert.assertEquals(extension.success, 6 + count);
    Assert.assertEquals(extension.thread, 10 - 1);
}
 
Example #11
Source File: FlowController.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
@GetMapping("/testSentinel")
public @ResponseBody
String testSentinel() {
    // 定义资源,具体的规则通过 dashboard 在页面中配置
    String resourceName = "testSentinel";
    Entry entry = null;
    String retVal;
    try{
        entry = SphU.entry(resourceName, EntryType.IN);
        retVal = "passed";
    }catch(BlockException e){
        retVal = "blocked";
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return retVal;
}
 
Example #12
Source File: FreqParamFlowController.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 热点参数限流
 * 构造不同的uid的值,并且以不同的频率来请求该方法,查看效果
 */
@GetMapping("/freqParamFlow")
public @ResponseBody
String freqParamFlow(@RequestParam("uid") Long uid,@RequestParam("ip") Long ip) {
    Entry entry = null;
    String retVal;
    try{
        // 只对参数 uid 的值进行限流,参数 ip 的值不进行限制
        entry = SphU.entry(resourceName, EntryType.IN,1,uid);
        retVal = "passed";
    }catch(BlockException e){
        retVal = "blocked";
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return retVal;
}
 
Example #13
Source File: FreqParamFlowController.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 热点参数限流
 */
@GetMapping("/freqParamFlowWithoutParam")
public @ResponseBody
String freqParamFlowWithoutParam(@RequestParam("uid") Long uid,@RequestParam("ip") Long ip) {
    Entry entry = null;
    String retVal;
    try{
        // 如果不传入任何参数,来查询热点参数限流的效果
        entry = SphU.entry(resourceName, EntryType.IN,1);
        retVal = "passed";
    }catch(BlockException e){
        retVal = "blocked";
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return retVal;
}
 
Example #14
Source File: ClusterFlowClientController.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 模拟流量请求该方法
 */
@GetMapping("/clusterFlow")
public @ResponseBody
String clusterFlow() {
    Entry entry = null;
    String retVal;
    try{
        entry = SphU.entry(RESOURCE_NAME, EntryType.IN,1);
        retVal = "passed";
    }catch(BlockException e){
        retVal = "blocked";
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return retVal;
}
 
Example #15
Source File: AbstractSentinelInterceptor.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    try {
        String resourceName = getResourceName(request);

        if (StringUtil.isNotEmpty(resourceName)) {
            // Parse the request origin using registered origin parser.
            String origin = parseOrigin(request);
            String contextName = getContextName(request);
            ContextUtil.enter(contextName, origin);
            Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN);

            setEntryInRequest(request, baseWebMvcConfig.getRequestAttributeName(), entry);
        }
        return true;
    } catch (BlockException e) {
        try {
            handleBlockException(request, response, e);
        } finally {
            ContextUtil.exit();
        }
        return false;
    }
}
 
Example #16
Source File: CommonTotalFilter.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest)request;

    Entry entry = null;
    try {
        ContextUtil.enter(WebServletConfig.WEB_SERVLET_CONTEXT_NAME);
        entry = SphU.entry(TOTAL_URL_REQUEST, ResourceTypeConstants.COMMON_WEB);
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse)response;
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException | ServletException | RuntimeException e2) {
        Tracer.trace(e2);
        throw e2;
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #17
Source File: WarmUpFlowDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            // token acquired, means pass
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(2000));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #18
Source File: WarmUpFlowDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #19
Source File: UserService.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 根据uid获取用户信息
 * @param uid uid
 * @return 用户信息
 */
public User getUser(Long uid){
    Entry entry = null;
    try {
        // 流控
        entry = SphU.entry(USER_RES);
        // 业务代码
        User user = new User();
        user.setUid(uid);
        user.setName("user-" + uid);
        return user;
    }catch(BlockException e){
        // 被限流了
        System.out.println("[getUser] has been protected! Time="+System.currentTimeMillis());
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return null;
}
 
Example #20
Source File: WarmUpRateLimiterFlowDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            // token acquired, means pass
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(2000));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #21
Source File: WarmUpRateLimiterFlowDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;
        try {
            entry = SphU.entry(KEY);
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }
        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #22
Source File: DemoController.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/link")
@ResponseBody
public String link() throws BlockException {

    Entry entry = SphU.entry("head1", EntryType.IN);

    Entry entry1 = SphU.entry("head2", EntryType.IN);
    Entry entry2 = SphU.entry("head3", EntryType.IN);
    Entry entry3 = SphU.entry("head4", EntryType.IN);

    entry3.exit();
    entry2.exit();
    entry1.exit();
    entry.exit();
    return "successfully create a call link";
}
 
Example #23
Source File: PullConsumerDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void doSomething(MessageExt message) {
    pool.submit(() -> {
        Entry entry = null;
        try {
            ContextUtil.enter(KEY);
            entry = SphU.entry(KEY, EntryType.OUT);

            // Your business logic here.
            System.out.printf("[%d][%s][Success: %d] Receive New Messages: %s %n", System.currentTimeMillis(),
                Thread.currentThread().getName(), SUCCESS_COUNT.addAndGet(1), new String(message.getBody()));
        } catch (BlockException ex) {
            // Blocked.
            System.out.println("Blocked: " + FAIL_COUNT.addAndGet(1));
        } finally {
            if (entry != null) {
                entry.exit();
            }
            ContextUtil.exit();
        }
    });
}
 
Example #24
Source File: MetricExitCallbackTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void onExit() {
    FakeMetricExtension extension = new FakeMetricExtension();
    MetricExtensionProvider.addMetricExtension(extension);

    MetricExitCallback exitCallback = new MetricExitCallback();
    StringResourceWrapper resourceWrapper = new StringResourceWrapper("resource", EntryType.OUT);
    int count = 2;
    Object[] args = {"args1", "args2"};
    long prevRt = 20;
    extension.rt = prevRt;
    extension.success = 6;
    extension.thread = 10;
    Context context = mock(Context.class);
    Entry entry = mock(Entry.class);

    // Mock current time
    long curMillis = System.currentTimeMillis();
    setCurrentMillis(curMillis);

    int deltaMs = 100;
    when(entry.getError()).thenReturn(null);
    when(entry.getCreateTimestamp()).thenReturn(curMillis - deltaMs);
    when(context.getCurEntry()).thenReturn(entry);
    exitCallback.onExit(context, resourceWrapper, count, args);
    Assert.assertEquals(prevRt + deltaMs, extension.rt);
    Assert.assertEquals(extension.success, 6 + count);
    Assert.assertEquals(extension.thread, 10 - 1);
}
 
Example #25
Source File: FlowQpsRunner.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;

        try {
            entry = SphU.entry(KEY);
            // token acquired, means pass
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }

        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #26
Source File: RtDegradeDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        tick();
        initDegradeRule();

        for (int i = 0; i < threadCount; i++) {
            Thread entryThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        Entry entry = null;
                        try {
                            TimeUnit.MILLISECONDS.sleep(5);
                            entry = SphU.entry(KEY);
                            // token acquired
                            pass.incrementAndGet();
                            // sleep 600 ms, as rt
                            TimeUnit.MILLISECONDS.sleep(600);
                        } catch (Exception e) {
                            block.incrementAndGet();
                        } finally {
                            total.incrementAndGet();
                            if (entry != null) {
                                entry.exit();
                            }
                        }
                    }
                }

            });
            entryThread.setName("working-thread");
            entryThread.start();
        }
    }
 
Example #27
Source File: FlowThreadDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println(
        "MethodA will call methodB. After running for a while, methodB becomes fast, "
            + "which make methodA also become fast ");
    tick();
    initFlowRule();

    for (int i = 0; i < threadCount; i++) {
        Thread entryThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Entry methodA = null;
                    try {
                        TimeUnit.MILLISECONDS.sleep(5);
                        methodA = SphU.entry("methodA");
                        activeThread.incrementAndGet();
                        Entry methodB = SphU.entry("methodB");
                        TimeUnit.MILLISECONDS.sleep(methodBRunningTime);
                        methodB.exit();
                        pass.addAndGet(1);
                    } catch (BlockException e1) {
                        block.incrementAndGet();
                    } catch (Exception e2) {
                        // biz exception
                    } finally {
                        total.incrementAndGet();
                        if (methodA != null) {
                            methodA.exit();
                            activeThread.decrementAndGet();
                        }
                    }
                }
            }
        });
        entryThread.setName("working thread");
        entryThread.start();
    }
}
 
Example #28
Source File: AbstractSofaRpcFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
protected void traceResponseException(SofaResponse response, Entry interfaceEntry, Entry methodEntry) {
    if (response.isError()) {
        SofaRpcException rpcException = new SofaRpcException(RpcErrorType.SERVER_FILTER, response.getErrorMsg());
        Tracer.traceEntry(rpcException, interfaceEntry);
        Tracer.traceEntry(rpcException, methodEntry);
    } else {
        Object appResponse = response.getAppResponse();
        if (appResponse instanceof Throwable) {
            Tracer.traceEntry((Throwable) appResponse, interfaceEntry);
            Tracer.traceEntry((Throwable) appResponse, methodEntry);
        }
    }
}
 
Example #29
Source File: FlowQpsRunner.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;

        try {
            entry = SphU.entry(resourceName);
            // token acquired, means pass
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }

        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #30
Source File: SentinelEntryBenchmark.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void doSomethingWithEntry() {
    Entry e0 = null;
    try {
        e0 = SphU.entry("benchmark");
        doSomething();
    } catch (BlockException e) {
    } finally {
        if (e0 != null) {
            e0.exit();
        }
    }
}