在Java中,需要每120分钟刷新一次的`assetoken`,并且你想使用Redis作为缓存来存储和管理这个令牌

时间:2024-10-25 12:10:03
import redis.clients.jedis.Jedis; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class AssetokenManager { private static final String REDIS_HOST = "localhost"; private static final int REDIS_PORT = 6379; private static final String ASSETOKEN_KEY = "assetoken"; private static final long TOKEN_EXPIRATION_TIME_MINUTES = 120; private static final long TOKEN_REFRESH_INTERVAL_MINUTES = TOKEN_EXPIRATION_TIME_MINUTES - 10; // 提前10分钟刷新 private Jedis jedis; private ScheduledExecutorService scheduler; public AssetokenManager() { this.jedis = new Jedis(REDIS_HOST, REDIS_PORT); this.scheduler = Executors.newScheduledThreadPool(1); // 初始化assetoken(这里应该是从某个服务获取实际的token) String initialToken = "initial_token_value"; storeAssetoken(initialToken); // 安排定时任务刷新token scheduler.scheduleAtFixedRate(this::refreshAssetoken, TOKEN_REFRESH_INTERVAL_MINUTES, TOKEN_REFRESH_INTERVAL_MINUTES, TimeUnit.MINUTES); } // 存储assetoken到Redis,并设置过期时间 private void storeAssetoken(String token) { jedis.setex(ASSETOKEN_KEY, (int) TimeUnit.MINUTES.toSeconds(TOKEN_EXPIRATION_TIME_MINUTES), token); } // 刷新assetoken(这里模拟重新获取token) private void refreshAssetoken() { // 在实际应用中,这里应该是调用某个API或服务来获取新的token String newToken = "new_token_value_" + System.currentTimeMillis(); storeAssetoken(newToken); System.out.println("Assetoken refreshed: " + newToken); } // 关闭资源 public void shutdown() { scheduler.shutdown(); jedis.close(); } public static void main(String[] args) { AssetokenManager manager = new AssetokenManager(); // 为了演示,让主线程等待一段时间,然后关闭资源 try { Thread.sleep(TimeUnit.MINUTES.toMillis(TOKEN_EXPIRATION_TIME_MINUTES * 3)); // 比如等待3个小时 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } manager.shutdown(); } }