Get id of Bandwidth which has zero tokens #185
-
Hello. I have a bucket with multiple limits.
Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
Yes, it is possible. There is Verbose API for doing stuff like this. It is not well documented on the Github Readme Pages, but I believe that javadocs is good enough. According to your particular task Verbose API can be used in following way: Bucket bucket = Bucket4j.builder()
.addLimit(Bandwidth.simple(10, Duration.ofSeconds(1)).withId("technical-limit"))
.addLimit(Bandwidth.simple(10000, Duration.ofHours(1)).withId("business-limit"))
.build();
...
int tokensToConsume = 100;
VerboseResult<Boolean> verboseResult = bucket.asVerbose().tryConsume(tokensToConsume);
boolean wasConsumed = verboseResult.getValue();
if (wasConsumed) {
// the limit is not exceeded
...
} else {
// limit is exceeded
Set<String> bandwidthIds = getBandwidthsThatHavingLessTokensThatRequired(verboseResult, tokensToConsume);
String bandwidthId = ???;
if( bandwidthIds.contains("technical-limit")) {
// do something
} else {
// do something else
}
}
}
private static Set<String> getBandwidthsThatHavingLessTokensThatRequired(VerboseResult<Boolean> verboseResult, int requiredTokens) {
BucketConfiguration configuration = verboseResult.getConfiguration();
Bandwidth[] bandwidths = configuration.getBandwidths();
BucketState state = verboseResult.getState();
Set<String> bandwidthsWithTokensLessThanRequired = new HashSet<>();
for (int i = 0; i < bandwidths.length; i++) {
if (state.getCurrentSize(i) < requiredTokens) {
bandwidthsWithTokensLessThanRequired.add(bandwidths[i].getId());
}
}
return bandwidthsWithTokensLessThanRequired;
} As you can see VerboseResult is a full snapshot of the bucket that is taken immediately after your operation. Then taken snapshot can be investigated in way that you need. |
Beta Was this translation helpful? Give feedback.
-
Unfortunately, it has package visibility. When I was writing example in previous post I placed it in the |
Beta Was this translation helpful? Give feedback.
-
Definitely no. If getCurrentSize behaved in the way that you described, snapshoting(as well as Verbose API) would not have sense. Firstly, snapshot is decoupled from original bucket, any change in the bucket after acquiring of snapshot does not affects the snapshot, and wise versa. |
Beta Was this translation helpful? Give feedback.
@dlakhtyuk
Yes, it is possible. There is Verbose API for doing stuff like this. It is not well documented on the Github Readme Pages, but I believe that javadocs is good enough.
According to your particular task Verbose API can be used in following way: