com.alibaba.csp.sentinel.SphU Java Examples

The following examples show how to use com.alibaba.csp.sentinel.SphU. 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: 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 #3
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 #4
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 #5
Source File: ParamFlowQpsRunner.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;
        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 #6
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 #7
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void directlyAsync() {
    try {
        final AsyncEntry entry = SphU.asyncEntry("test-async-not-nested");

        this.invoke("abc", result -> {
            // If no nested entry later, we don't have to wrap in `ContextUtil.runOnContext()`.
            try {
                // Here to handle the async result (without other entry).
            } finally {
                // Exit the async entry.
                entry.exit();
            }
        });
    } catch (BlockException e) {
        // Request blocked, handle the exception.
        e.printStackTrace();
    }
}
 
Example #8
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 #9
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 #10
Source File: SentinelReactorSubscriber.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void entryWhenSubscribed() {
    ContextConfig sentinelContextConfig = entryConfig.getContextConfig();
    if (sentinelContextConfig != null) {
        // If current we're already in a context, the context config won't work.
        ContextUtil.enter(sentinelContextConfig.getContextName(), sentinelContextConfig.getOrigin());
    }
    try {
        AsyncEntry entry = SphU.asyncEntry(entryConfig.getResourceName(), entryConfig.getEntryType(),
            entryConfig.getAcquireCount(), entryConfig.getArgs());
        this.currentEntry = entry;
        actual.onSubscribe(this);
    } catch (BlockException ex) {
        // Mark as completed (exited) explicitly.
        entryExited.set(true);
        // Signal cancel and propagate the {@code BlockException}.
        cancel();
        actual.onSubscribe(this);
        actual.onError(ex);
    } finally {
        if (sentinelContextConfig != null) {
            ContextUtil.exit();
        }
    }
}
 
Example #11
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 #12
Source File: FlowPartialIntegrationTest.java    From Sentinel-Dashboard-Nacos 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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: SentinelStart.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	// 配置规则.
	initFlowRules();

	while (true) {
		// 1.5.0 版本开始可以直接利用 try-with-resources 特性,自动 exit entry
		try (Entry entry = SphU.entry("HelloWorld")) {
			// 被保护的逻辑
			System.out.println("hello world");
		} catch (BlockException ex) {
			// 处理被流控的逻辑
			System.out.println("blocked!");
		}
		Thread.sleep(10);
	}
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: AsyncEntryDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void anotherAsync() {
    try {
        final AsyncEntry entry = SphU.asyncEntry("test-another-async");

        CompletableFuture.runAsync(() -> {
            ContextUtil.runOnContext(entry.getAsyncContext(), () -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                    // Normal entry nested in asynchronous entry.
                    anotherSyncInAsync();

                    System.out.println("Async result: 666");
                } catch (InterruptedException e) {
                    // Ignore.
                } finally {
                    entry.exit();
                }
            });
        });
    } catch (BlockException ex) {
        ex.printStackTrace();
    }
}
 
Example #24
Source File: AsyncEntryDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void directlyAsync() {
    try {
        final AsyncEntry entry = SphU.asyncEntry("test-async-not-nested");

        this.invoke("abc", result -> {
            // If no nested entry later, we don't have to wrap in `ContextUtil.runOnContext()`.
            try {
                // Here to handle the async result (without other entry).
            } finally {
                // Exit the async entry.
                entry.exit();
            }
        });
    } catch (BlockException e) {
        // Request blocked, handle the exception.
        e.printStackTrace();
    }
}
 
Example #25
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 #26
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 #27
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 #28
Source File: SentinelReactorSubscriber.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void entryWhenSubscribed() {
    ContextConfig sentinelContextConfig = entryConfig.getContextConfig();
    if (sentinelContextConfig != null) {
        // If current we're already in a context, the context config won't work.
        ContextUtil.enter(sentinelContextConfig.getContextName(), sentinelContextConfig.getOrigin());
    }
    try {
        AsyncEntry entry = SphU.asyncEntry(entryConfig.getResourceName(), entryConfig.getResourceType(),
            entryConfig.getEntryType(), entryConfig.getAcquireCount(), entryConfig.getArgs());
        this.currentEntry = entry;
        actual.onSubscribe(this);
    } catch (BlockException ex) {
        // Mark as completed (exited) explicitly.
        entryExited.set(true);
        // Signal cancel and propagate the {@code BlockException}.
        cancel();
        actual.onSubscribe(this);
        actual.onError(ex);
    } finally {
        if (sentinelContextConfig != null) {
            ContextUtil.exit();
        }
    }
}
 
Example #29
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 #30
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;
    }
}