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) {
}
}
}