Bat/src/main/java/cc/fascinated/bat/service/UserService.java

81 lines
2.4 KiB
Java
Raw Normal View History

2024-06-24 13:56:01 +01:00
package cc.fascinated.bat.service;
import cc.fascinated.bat.common.TimerUtils;
2024-07-01 01:33:52 +01:00
import cc.fascinated.bat.event.EventListener;
2024-06-25 11:55:26 +01:00
import cc.fascinated.bat.model.BatUser;
import com.mongodb.client.model.Filters;
import lombok.Getter;
2024-06-24 13:56:01 +01:00
import lombok.NonNull;
import lombok.extern.log4j.Log4j2;
import org.bson.Document;
2024-06-24 13:56:01 +01:00
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
2024-06-27 23:51:40 +01:00
import java.util.concurrent.TimeUnit;
2024-06-24 13:56:01 +01:00
/**
* @author Fascinated (fascinated7)
*/
2024-06-28 03:01:21 +01:00
@Service
@Log4j2(topic = "User Service")
2024-06-28 03:01:21 +01:00
@Getter
@DependsOn({"discordService", "mongoService"})
2024-07-01 01:33:52 +01:00
public class UserService implements EventListener {
private static final long SAVE_INTERVAL = TimeUnit.MINUTES.toMillis(5);
2024-06-24 13:56:01 +01:00
/**
* The cached users
2024-06-24 13:56:01 +01:00
*/
private final Map<String, BatUser> users = new HashMap<>();
2024-06-24 13:56:01 +01:00
@Autowired
public UserService() {
TimerUtils.scheduleRepeating(() -> {
long before = System.currentTimeMillis();
for (BatUser user : users.values()) {
user.save();
}
log.info("Saved {} users in {}ms", users.size(), System.currentTimeMillis() - before);
}, SAVE_INTERVAL, SAVE_INTERVAL);
2024-06-24 13:56:01 +01:00
}
/**
* Gets a user by its ID
2024-06-24 13:56:01 +01:00
*
* @param id The ID of the user
* @return The user
*/
public BatUser getUser(@NonNull String id) {
long before = System.currentTimeMillis();
// User is cached
if (users.containsKey(id)) {
return users.get(id);
}
// User is not cached
Document document = MongoService.INSTANCE.getUsersCollection().find(Filters.eq("_id", id)).first();
if (document != null) {
BatUser user = new BatUser(id, document);
users.put(id, user);
log.info("Loaded user \"{}\" in {}ms", user.getName(),System.currentTimeMillis() - before);
return user;
2024-06-24 13:56:01 +01:00
}
// New user
BatUser user = new BatUser(id, new Document());
users.put(id, user);
log.info("Created user \"{}\" - \"{}\"", user.getName(), user.getId());
2024-06-24 13:56:01 +01:00
return user;
}
2024-07-01 01:33:52 +01:00
@Override
public void onSpringShutdown() {
log.info("Saving all users before shutdown...");
for (BatUser user : users.values()) {
user.save();
}
log.info("Saved all users.");
}
2024-06-24 13:56:01 +01:00
}