Java Code Examples for com.alibaba.csp.sentinel.SphU#entry()

The following examples show how to use com.alibaba.csp.sentinel.SphU#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: 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 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: 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 4
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 5
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 6
Source File: FlowQpsDemo.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 7
Source File: SlotChainBuilderSpiDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // You will see this in record.log, indicating that the custom slot chain builder is activated:
    // [SlotChainProvider] Global slot chain builder resolved: com.alibaba.csp.sentinel.demo.slot.DemoSlotChainBuilder
    Entry entry = null;
    try {
        entry = SphU.entry("abc");
    } catch (BlockException ex) {
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
    }
}
 
Example 8
Source File: ClusterNodeBuilderTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void clusterNodeBuilder_normal() throws Exception {
    ContextUtil.enter("entry1", "caller1");

    Entry nodeA = SphU.entry("nodeA");

    Node curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN = (DefaultNode)curNode;
    assertTrue(dN.getClusterNode().getOriginCountMap().containsKey("caller1"));
    assertSame(nodeA.getOriginNode(), dN.getClusterNode().getOrCreateOriginNode("caller1"));

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();

    ContextUtil.enter("entry4", "caller2");

    nodeA = SphU.entry("nodeA");

    curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN1 = (DefaultNode)curNode;
    assertTrue(dN1.getClusterNode().getOriginCountMap().containsKey("caller2"));
    assertNotSame(dN1, dN);

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();
}
 
Example 9
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    initFlowRule();

    AsyncEntryDemo service = new AsyncEntryDemo();

    // Expected invocation chain:
    //
    // EntranceNode: machine-root
    // -EntranceNode: async-context
    // --test-top
    // ---test-sync
    // ---test-async
    // ----test-another-async
    // -----test-another-sync-in-async
    // ----test-sync-in-async
    ContextUtil.enter("async-context", "originA");
    Entry entry = null;
    try {
        entry = SphU.entry("test-top");
        System.out.println("Do something...");
        service.doAsyncThenSync();
    } catch (BlockException ex) {
        // Request blocked, handle the exception.
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }

    TimeUnit.SECONDS.sleep(20);
}
 
Example 10
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void anotherSyncInAsync() {
    Entry entry = null;
    try {
        entry = SphU.entry("test-another-sync-in-async");
    } catch (BlockException ex) {
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
    }
}
 
Example 11
Source File: ClusterNodeBuilderTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void clusterNodeBuilder_normal() throws Exception {
    ContextUtil.enter("entry1", "caller1");

    Entry nodeA = SphU.entry("nodeA");

    Node curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN = (DefaultNode)curNode;
    assertTrue(dN.getClusterNode().getOriginCountMap().containsKey("caller1"));
    assertSame(nodeA.getOriginNode(), dN.getClusterNode().getOrCreateOriginNode("caller1"));

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();

    ContextUtil.enter("entry4", "caller2");

    nodeA = SphU.entry("nodeA");

    curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN1 = (DefaultNode)curNode;
    assertTrue(dN1.getClusterNode().getOriginCountMap().containsKey("caller2"));
    assertNotSame(dN1, dN);

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();
}
 
Example 12
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void fetchSync() {
    Entry entry = null;
    try {
        entry = SphU.entry("test-sync");
    } catch (BlockException ex) {
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
    }
}
 
Example 13
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 14
Source File: NodeSelectorTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public void testMultipleLayer() throws Exception {
    // TODO: fix this
    ContextUtil.enter("entry1", "appA");

    Entry nodeA = SphU.entry("nodeA");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeA);

    DefaultNode dnA = (DefaultNode)nodeA.getCurNode();
    assertNotNull(dnA);
    assertSame("nodeA", dnA.getId().getName());

    Entry nodeB = SphU.entry("nodeB");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeB);
    DefaultNode dnB = (DefaultNode)nodeB.getCurNode();
    assertNotNull(dnB);
    assertTrue(dnA.getChildList().contains(dnB));

    Entry nodeC = SphU.entry("nodeC");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeC);
    DefaultNode dnC = (DefaultNode)nodeC.getCurNode();
    assertNotNull(dnC);
    assertTrue(dnB.getChildList().contains(dnC));

    if (nodeC != null) {
        nodeC.exit();
    }
    assertSame(ContextUtil.getContext().getCurEntry(), nodeB);

    if (nodeB != null) {
        nodeB.exit();
    }
    assertSame(ContextUtil.getContext().getCurEntry(), nodeA);

    if (nodeA != null) {
        nodeA.exit();
    }
    assertNull(ContextUtil.getContext().getCurEntry());
    ContextUtil.exit();

}
 
Example 15
Source File: AsyncEntryDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void fetchSyncInAsync() {
    Entry entry = null;
    try {
        entry = SphU.entry("test-sync-in-async");
    } catch (BlockException ex) {
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
    }
}
 
Example 16
Source File: FlowThreadDemo.java    From Sentinel-Dashboard-Nacos 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 17
Source File: CommonTotalFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest)request;
    String target = FilterUtil.filterTarget(sRequest);
    target = WebCallbackManager.getUrlCleaner().clean(target);

    Entry entry = null;
    try {
        ContextUtil.enter(target);
        entry = SphU.entry(TOTAL_URL_REQUEST);
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse)response;
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException e2) {
        Tracer.trace(e2);
        throw e2;
    } catch (ServletException e3) {
        Tracer.trace(e3);
        throw e3;
    } catch (RuntimeException e4) {
        Tracer.trace(e4);
        throw e4;
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example 18
Source File: OverloadMonitor.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
    Entry entry = null;
    try {
        entry=  SphU.entry(context.getServiceName());
    } catch (BlockException ex){
        logger.warn("request was block by overload monitor, serviceName:{}.", context.getServiceName());
        throw ex;
    }
    finally {
        if (entry != null) {
            entry.exit();
        }
    }
}
 
Example 19
Source File: ExceptionCountDegradeDemo.java    From Sentinel with Apache License 2.0 4 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() {
                int count = 0;
                while (true) {
                    count++;
                    Entry entry = null;
                    try {
                        Thread.sleep(20);
                        entry = SphU.entry(KEY);
                        // token acquired, means pass
                        pass.addAndGet(1);
                        if (count % 2 == 0) {
                            // biz code raise an exception.
                            throw new RuntimeException("throw runtime ");
                        }
                    } catch (BlockException e) {
                        block.addAndGet(1);
                    } catch (Throwable t) {
                        bizException.incrementAndGet();
                        Tracer.trace(t);
                    } finally {
                        total.addAndGet(1);
                        if (entry != null) {
                            entry.exit();
                        }
                    }
                }
            }

        });
        entryThread.setName("working-thread");
        entryThread.start();
    }

}
 
Example 20
Source File: CommonFilter.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest) request;
    Entry urlEntry = null;

    try {
        String target = FilterUtil.filterTarget(sRequest);
        // Clean and unify the URL.
        // For REST APIs, you have to clean the URL (e.g. `/foo/1` and `/foo/2` -> `/foo/:id`), or
        // the amount of context and resources will exceed the threshold.
        UrlCleaner urlCleaner = WebCallbackManager.getUrlCleaner();
        if (urlCleaner != null) {
            target = urlCleaner.clean(target);
        }

        // If you intend to exclude some URLs, you can convert the URLs to the empty string ""
        // in the UrlCleaner implementation.
        if (!StringUtil.isEmpty(target)) {
            // Parse the request origin using registered origin parser.
            String origin = parseOrigin(sRequest);
            String contextName = webContextUnify ? WebServletConfig.WEB_SERVLET_CONTEXT_NAME : target;
            ContextUtil.enter(contextName, origin);

            if (httpMethodSpecify) {
                // Add HTTP method prefix if necessary.
                String pathWithHttpMethod = sRequest.getMethod().toUpperCase() + COLON + target;
                urlEntry = SphU.entry(pathWithHttpMethod, ResourceTypeConstants.COMMON_WEB, EntryType.IN);
            } else {
                urlEntry = SphU.entry(target, ResourceTypeConstants.COMMON_WEB, EntryType.IN);
            }
        }
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse) response;
        // Return the block page, or redirect to another URL.
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException | ServletException | RuntimeException e2) {
        Tracer.traceEntry(e2, urlEntry);
        throw e2;
    } finally {
        if (urlEntry != null) {
            urlEntry.exit();
        }
        ContextUtil.exit();
    }
}