zoukankan      html  css  js  c++  java
  • sessionContext example

    how to manage sessionContext data, need to be deeply looked inside.

    import com.google.common.collect.Maps;
    import com.tqmall.tqmallstall.model.UserAddress;
    import com.tqmall.tqmallstall.model.Users;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;

    import java.util.Map;

    /**
    * <p> 业务上下文。session可以放在这里
    * <b>重要:所有的init必须跟着一个resetContext</b>
    */
    @Slf4j
    @Component
    public class ContextHolder {
    // ------------------------------ FIELDS ------------------------------

    /**
    * key为threadId
    */
    private Map<Long, SessionContext> sessionContextMap = Maps.newConcurrentMap();


    // --------------------- GETTER / SETTER METHODS ---------------------

    public SessionContext getSessionContext() {
    final SessionContext sessionContext = sessionContextMap.get(currentThreadId());
    if (sessionContext == null) {
    throw new IllegalStateException("session context not properly initialized " +
    "or initSessionContext method doesn't has been invoked!.");
    }
    return sessionContext;
    }


    void initSessionContext(final Users user, final UserAddress address,
    Integer cityId, final Integer warehouseId,
    Integer accountId) {
    if (isSessionContextInitialized()) {
    throw new IllegalStateException("duplicated initialization of sessionContext,check if this method invoked somewhere!!");
    }
    if (log.isDebugEnabled()) {
    log.debug("init session context, threadId:" + Thread.currentThread().getId());
    }
    sessionContextMap.put(currentThreadId(), new SessionContext(user,
    address, cityId, warehouseId, accountId));
    }

    private long currentThreadId() {
    return Thread.currentThread().getId();
    }

    private boolean isSessionContextInitialized() {
    return sessionContextMap.get(currentThreadId()) != null;
    }

    public void resetContext() {
    if (log.isDebugEnabled()) {
    log.debug("reset contextHolder, thread:"
    + Thread.currentThread().getId());
    }
    try {
    sessionContextMap.remove(currentThreadId());
    } catch (Throwable ignored) {
    }
    }

    public void removeContext() {
    if (log.isDebugEnabled()) {
    log.debug("removeContext contextHolder, thread:" + Thread.currentThread().getId());
    }
    try {
    if (!CollectionUtils.isEmpty(sessionContextMap)) {
    sessionContextMap.clear();
    }
    } catch (Throwable ignored) {
    }
    }
    }



  • 相关阅读:
    动态规划01背包
    动态规划矩阵连乘
    分治法归并排序
    动态规划最长公共子序列
    贪心算法活动安排
    分治法二分查找
    vue 可拖拽可缩放 vuedraggableresizable 组件常用总结
    rifilter in python discussed in 3delight
    3delight linear work flow
    pixar stereo rendering doc
  • 原文地址:https://www.cnblogs.com/hzorac/p/5249434.html
Copyright © 2011-2022 走看看