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

时间:2012-05-01 10:31:20

标签: java arrays data-structures arraylist

我想在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;    
    }   

}

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

祝福

3 个答案:

答案 0 :(得分:5)

大概每个用户都有一个唯一的ID,因此Map实现似乎是一个明智的选择,其中键是用户ID,值为ActiveSessionsObj

Map<String, ActiveSessionsObj> cache =
    new HashMap<String, ActiveSessionsObj>();

请参阅Javadoc以添加put())并从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));
}

答案 1 :(得分:2)

基本上,您不需要SessionCache中的列表,只需定义一些私有属性,并提供一些重用的get set方法来访问这些属性。

答案 2 :(得分:2)

您应该使用Map接口的实例来存储数据对象。您需要确保每个用户都有一个唯一的密钥;如果你这样做,你可以使用这个键作为HashMap

的输入

此外,为了使SessionCache更少依赖于ActiveSessionsObj的内部细节,您应该使您的addCache方法采用其中一个ActiveSessionsObjs。使用地图实现,这看起来更像是:

public void addCache(String key, ActiveSessionsObj data){

    dataMap.put(key, data);

}   

最好不要从SessionCache返回Map,否则会破坏缓存的encapsulation

相关问题