java 使用HashMap缓存对象

需求:在代码中创建HashMap对象,存储相应对象的键——值对,在需要时,通过key,调用相应的对象,减少数据库的访问量

实现过程:

1、创建HashMap对象:

private HashMap<String, MessagesParticipatorInformation> chatParticipator = new HashMap<>();

2、给chatParticipator中添加相应的键与对象(数据库中所有的Member、shop对象,键为其对应的id):

private void refreshChatPaticipatorMap() {
  HashMap<String, MessagesParticipatorInformation> map = new HashMap<>();
  // All Shop Information
  List<Shop> shopList = shopService.getList();
  for (int i = 0; i < shopList.size(); i++) {
  Shop shop = shopList.get(i);
  MessagesParticipatorInformation mpi = new MessagesParticipatorInformation();
  mpi.setId(shop.getId());
  mpi.setAvatar(shop.getLogo());
  mpi.setNickName(shop.getName());
  map.put(shop.getId(), mpi);
  this.chatParticipator = map;
 }
  // All Member Information
  List<Member> memberList = memberService.getList();
  for (int i = 0; i < memberList.size(); i++) {
  Member member = memberList.get(i);
  MessagesParticipatorInformation mpi2 = new MessagesParticipatorInformation();
  mpi2.setId(member.getId());
  mpi2.setAvatar(member.getAvatar());
  mpi2.setNickName(member.getNickName());
  map.put(member.getId(), mpi2);
  this.chatParticipator = map;
 }
}

3、创建通过id获取对象的方法:

private MessagesParticipatorInformation getChatPaticipatorById(String ownerId) {
MessagesParticipatorInformation msg = null;
/**
* Parameter check
*/
if (ownerId != null && !ownerId.equals("")) {
/**
* Refresh the map, if necessary.
*/
if (this.chatParticipator.isEmpty()) {
refreshChatPaticipatorMap();
}

if (this.chatParticipator.containsKey(ownerId)) {
/**
* Use id to find the expected message
*/
msg = this.chatParticipator.get(ownerId);
// To-Do
    }
 }

if (msg == null) {
// Set to default values, if nothing found in the map.
msg = new MessagesParticipatorInformation();
String defaultAvater = "http://xiaoyouhui2018.oss-cn-beijing.aliyuncs.com/notice/cover/20190311/1552297610973875.png";
String defaultNickName = "校友汇";

msg.setId(ownerId);
msg.setAvatar(defaultAvater);
msg.setNickName(defaultNickName);
  }

return msg;
}

4、创建一个接口测试效果:

@RequestMapping(value = "v2/member/blog/uname")
public Object getChatPaticipatorByIds(@RequestParam(value = "id") String id) {
    MessagesParticipatorInformation msg = new MessagesParticipatorInformation();
    msg = getChatPaticipatorById(id);
    return APIResult.createSuccess(msg);
}

5、在程序中调用getChatPaticipatorById(String ownerId)方法,获取相应的对象,如下(消息对话中,获取对方信息):

MessagesParticipatorInformation msg = null;
if (member.getId().equals(messages.getMessagesFrom())) {
    msg = getChatPaticipatorById(messages.getMessagesTo());
} else {
        msg = getChatPaticipatorById(messages.getMessagesFrom());
}

注:该方法的使用过程中,关键是:相应的键——值对存入Map中

                                                          通过键获取HashMap中对象的方法,需求:HashMap为空、定时刷新创建HashMap的方法

                                                          在程序中获取相应的key,通过键获取HashMap中对象的方法获取对象。

原文地址:https://www.cnblogs.com/qqzhulu/p/10533120.html