如何在Java中创建缓存以存储用户会话

Pet*_*zov 0 java arrays arraylist data-structures

我想在java中创建缓存来存储用户会话.它就像一个缓存,可以为每个用户存储5个元素.我需要一些必须能够记住这些数据的java数据结构.到目前为止,我创建了这个Java代码:

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SessionCache {

    public SessionCache() {
    }

    /* Create object to store sessions */
    private List<ActiveSessionsObj> dataList = new ArrayList<>();

    public static class ActiveSessionsObj {
        private int one;
        private int two;
        private int three;
        private int four;
        private int five;

        private ActiveSessionsObj(int one, int two, int three, int four, int five) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    }

    public List<ActiveSessionsObj> addCache(int one, int two, int three, int four, int five){

        dataList.add(new ActiveSessionsObj(
                        one,
                        two,
                        three,
                        four,
                        five));
          return dataList;    
    }   

}
Run Code Online (Sandbox Code Playgroud)

我是java的新手,我需要一个帮助,我可以如何向结构中添加数据以及如何从结构中删除数据.我需要使用密钥来完成此操作.这可能吗?或者是否有更合适的数据结构来根据mu需求存储数据?

最好的祝愿

hmj*_*mjd 5

据推测每个用户都有一个唯一的id,因此一个Map实现似乎是一个明智的选择,其中键是用户ID,值是ActiveSessionsObj:

Map<String, ActiveSessionsObj> cache =
    new HashMap<String, ActiveSessionsObj>();
Run Code Online (Sandbox Code Playgroud)

请参阅Javadoc以从中添加(put())和remove(remove())元素Map:

public void addCache(String user_id,int one,int two,int three,int four,int five)
{
    // You may want to check if an entry already exists for a user,
    // depends on logic in your application. Otherwise, this will
    // replace any previous entry for 'user_id'.
    cache.put(user_id, new ActiveSessionsObj(one, two, three, four, five));
}
Run Code Online (Sandbox Code Playgroud)