package cn.edu.zjvtit.cloudstorage.apiservice.store;

import cn.edu.zjvtit.cloudstorage.apiservice.ApiServiceApplication;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class DataServerStore {
    private final Map<String, Long> serverHeart = new HashMap<>();

    public synchronized void receivedHeart(String addr) {
        // 保存服务端心跳
        this.serverHeart.put(addr, System.currentTimeMillis() / 1000);
    }
    public Map<String,Long> getServerHeart(){
        return this.serverHeart;
    }
    Set<String> getServerList() {
        // 获取服务器列表
        return this.serverHeart.keySet();
    }

    public String selectRandomServer() {
        //随机选择一个服务器
        Set<String> serverList = getServerList();
        if (serverList.size() == 0) {
            return null;
        }
        int index = (int) (Math.random() * serverList.size());
        return serverList.toArray()[index].toString();
    }
}
