In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the knowledge of "how to use the RateLimiter of guava". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
About current restriction
The commonly used current-limiting algorithms are leaky bucket algorithm and token bucket algorithm. Guava's RateLimiter uses token bucket algorithm, which puts tokens into the bucket at a fixed frequency, such as 10 tokens a second. The actual business obtains tokens from the bucket before each response request, and only the request that gets the token will be successfully responded. There are two ways to obtain it: blocking waiting for tokens or failing to get them immediately. The following figure:
In this actual combat, we use guava's RateLimiter. The scenario is that spring mvc applies for a token from the bucket when processing the request, and responds successfully when the application is received. If the application is not available, it directly returns the failure.
Actual combat development
Create a maven project to add guava dependencies to pom:
Com.google.guava guava 18.0
Encapsulate the current limiting service into a class AccessLimitService, provide the tryAcquire () method, which is used to attempt to obtain a token, and return true to indicate that it has been obtained, as shown below:
@ Servicepublic class AccessLimitService {/ / issue only 5 tokens per second RateLimiter rateLimiter = RateLimiter.create (5.0); / * attempt to get tokens * @ return * / public boolean tryAcquire () {return rateLimiter.tryAcquire ();}}
The caller is a normal controller. Each time he receives a request, he tries to obtain a token and print different information about success and failure, as shown below:
@ Controllerpublic class HelloController {private static SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); @ Autowired private AccessLimitService accessLimitService @ RequestMapping ("/ access") @ ResponseBody public String access () {/ / attempt to get token if (accessLimitService.tryAcquire ()) {/ / simulate business execution 500ms try {Thread.sleep (500) } catch (InterruptedException e) {e.printStackTrace ();} return "aceess success [" + sdf.format (new Date ()) + "]";} else {return "aceess limit [" + sdf.format (new Date ()) + "]" }}}
The above is the server code, which can be packaged and deployed on tomcat. Next, we write a class in which ten threads concurrently access the controller written above:
Public class AccessClient {ExecutorService fixedThreadPool = Executors.newFixedThreadPool (10); / * get request * @ param realUrl * @ return * / public static String sendGet (URL realUrl) {String result = ""; BufferedReader in = null; try {/ / Open connection to URL URLConnection connection = realUrl.openConnection () / / set general request properties connection.setRequestProperty ("accept", "* / *"); connection.setRequestProperty ("connection", "Keep-Alive"); connection.setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1 Sv1)") / / establish the actual connection connection.connect (); / / define the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (connection.getInputStream (); String line; while ((line = in.readLine ())! = null) {result + = line }} catch (Exception e) {System.out.println ("an exception occurred sending a GET request!" + e); e.printStackTrace ();} / / use the finally block to close the input stream finally {try {if (in! = null) {in.close ();}} catch (Exception e2) {e2.printStackTrace () }} return result;} public void access () throws Exception {final URL url = new URL ("http://localhost:8080/guavalimitdemo/access"); for (int iTuno [)]
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 283
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.