请写出用Java实现利用redis以及hashmap获取某个接口在一天里被某个用户调用的次数的代码
时间: 2023-05-28 21:06:27 浏览: 124
假设需要获取的接口为 "/api/getData",用户ID为 "123456",并且已经配置好了Redis连接池和Jedis实例。以下是实现代码:
```java
import java.util.HashMap;
import java.util.Map;
import redis.clients.jedis.Jedis;
public class ApiUsageCounter {
private static final String API_USAGE_KEY_PREFIX = "api_usage:";
private Jedis jedis;
public ApiUsageCounter(Jedis jedis) {
this.jedis = jedis;
}
public void incrementApiUsage(String api, String userId) {
String key = API_USAGE_KEY_PREFIX + api;
String field = userId + ":" + getCurrentDate();
jedis.hincrBy(key, field, 1);
}
public long getApiUsage(String api, String userId) {
String key = API_USAGE_KEY_PREFIX + api;
String field = userId + ":" + getCurrentDate();
String value = jedis.hget(key, field);
return value == null ? 0 : Long.parseLong(value);
}
public Map<String, Long> getApiUsageAllUsers(String api) {
String key = API_USAGE_KEY_PREFIX + api;
Map<String, String> fieldValues = jedis.hgetAll(key);
Map<String, Long> result = new HashMap<>();
for (String field : fieldValues.keySet()) {
String[] parts = field.split(":");
String userId = parts[0];
String date = parts[1];
if (date.equals(getCurrentDate())) {
long count = Long.parseLong(fieldValues.get(field));
result.put(userId, count);
}
}
return result;
}
private String getCurrentDate() {
return LocalDate.now().format(DateTimeFormatter.ISO_DATE);
}
}
```
使用示例:
```java
// 初始化Redis连接池和Jedis实例
JedisPool jedisPool = new JedisPool("localhost", 6379);
Jedis jedis = jedisPool.getResource();
// 创建ApiUsageCounter实例
ApiUsageCounter counter = new ApiUsageCounter(jedis);
// 假设有一次调用
counter.incrementApiUsage("/api/getData", "123456");
// 获取用户123456在今天调用"/api/getData"的次数
long count = counter.getApiUsage("/api/getData", "123456");
// 获取所有用户今天调用"/api/getData"的次数
Map<String, Long> counts = counter.getApiUsageAllUsers("/api/getData");
// 关闭Jedis实例和Redis连接池
jedis.close();
jedisPool.close();
```
阅读全文