修改代码

parent 61478609
...@@ -18,9 +18,11 @@ import org.apache.commons.lang3.StringUtils; ...@@ -18,9 +18,11 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import javax.persistence.Cacheable;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
...@@ -32,166 +34,160 @@ import java.util.concurrent.TimeUnit; ...@@ -32,166 +34,160 @@ import java.util.concurrent.TimeUnit;
@Service @Service
public class SessionServiceImpl implements ISessionService { public class SessionServiceImpl implements ISessionService {
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate; private RedisTemplate<String, String> stringRedisTemplate;
@Override @Override
public AuthBean createSession(Long channelId, Long createdFrom, String appChannel, User user, Merchant merchant) { public AuthBean createSession(Long channelId, Long createdFrom, String appChannel, User user, Merchant merchant) {
AuthBean authBean = new AuthBean(); AuthBean authBean = new AuthBean();
LoginProperties properties = new LoginProperties(); LoginProperties properties = new LoginProperties();
properties.setAppChannel(appChannel); properties.setAppChannel(appChannel);
if(null!=merchant){ if (null != merchant) {
properties.setMerchantName(merchant.getName()); properties.setMerchantName(merchant.getName());
}
properties.setChannelId(channelId);
properties.setCreatedFrom(createdFrom);
//找到用户
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
// String sessionId = sessionService.findSessionIdByUserIdAndMerchant(user.getId(), merchant);
if (org.apache.commons.lang.StringUtils.isNotEmpty(sessionId)) {
SessionStruct sessionStruct = findSessionBySessionId(sessionId);
sessionStruct.setAttribute("channelId", String.valueOf(channelId));
sessionStruct.setAttribute("createdFrom", String.valueOf(createdFrom));
sessionStruct.setAttribute("appChannel", String.valueOf(appChannel));
authBean.setPhoneNo(user.getPhoneNo());
authBean.setToken(sessionStruct.getSid());
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel);
return authBean;
}
SessionStruct sessionStruct = createSessionAndPersist(user, properties);
authBean.setPhoneNo(user.getPhoneNo());
authBean.setToken(sessionStruct.getSid());
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel);
return authBean;
} }
properties.setChannelId(channelId);
properties.setCreatedFrom(createdFrom); @Override
//找到用户 public SessionStruct createSessionAndPersist(User user, LoginProperties properties) {
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties); SessionStruct sessionStruct;
// String sessionId = sessionService.findSessionIdByUserIdAndMerchant(user.getId(), merchant); //获取sessionid
if (org.apache.commons.lang.StringUtils.isNotEmpty(sessionId)) { String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
SessionStruct sessionStruct = findSessionBySessionId(sessionId); if (StringUtils.length(sessionId) == 36) {
sessionStruct.setAttribute("channelId", String.valueOf(channelId)); sessionStruct = findSessionBySessionId(sessionId);
sessionStruct.setAttribute("createdFrom", String.valueOf(createdFrom)); if (sessionStruct == null) {
sessionStruct.setAttribute("appChannel", String.valueOf(appChannel)); sessionStruct = newSession(user, properties);
authBean.setPhoneNo(user.getPhoneNo()); } else {
authBean.setToken(sessionStruct.getSid()); sessionStruct.getValues().setLoginProperties(properties);
persistSession(sessionStruct.getSid(), sessionStruct.getValues()); }
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel); persistSession(sessionStruct.getSid(), sessionStruct.getValues());
return authBean; } else {
sessionStruct = newSession(user, properties);
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
}
return sessionStruct;
} }
SessionStruct sessionStruct = createSessionAndPersist(user, properties);
authBean.setPhoneNo(user.getPhoneNo()); @Override
authBean.setToken(sessionStruct.getSid()); public String findSessionIdByUserIdLoginProperties(Long userId, LoginProperties properties) {
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel); return stringRedisTemplate.opsForValue().get(generateLoginPropertiesKey(userId, properties));
return authBean;
}
@Override
public SessionStruct createSessionAndPersist(User user, LoginProperties properties) {
SessionStruct sessionStruct;
//获取sessionid
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
if (StringUtils.length(sessionId) == 36) {
sessionStruct = findSessionBySessionId(sessionId);
if (sessionStruct == null) {
sessionStruct = newSession(user, properties);
} else {
sessionStruct.getValues().setLoginProperties(properties);
}
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
} else {
sessionStruct = newSession(user, properties);
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
} }
return sessionStruct;
} private String generateLoginPropertiesKey(Long userId, LoginProperties properties) {
if ("baitiao".equals(properties.getMerchantName())) {
@Override return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom();
public String findSessionIdByUserIdLoginProperties(Long userId, LoginProperties properties) { } else {
return stringRedisTemplate.opsForValue().get(generateLoginPropertiesKey(userId, properties)); return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName();
} }
}
private String generateLoginPropertiesKey(Long userId, LoginProperties properties) {
if ("baitiao".equals(properties.getMerchantName())) { @Override
return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom(); public String findSessionValueBySessionId(String sessionId) {
} else { String result = stringRedisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + sessionId);
return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName(); return StringUtils.defaultString(result, "");
}
@Override
public SessionStruct newSession(User user, LoginProperties loginProperties) {
Timestamp now = new Timestamp(System.currentTimeMillis());
SessionStruct sessionStruct = new SessionStruct();
SessionValue sessionValue = new SessionValue();
sessionStruct.setSid(UUID.randomUUID().toString());
sessionValue.setCreatedAt(now);
sessionValue.setLastAccessTime(now);
sessionValue.setUser(user);
sessionValue.setLoginProperties(loginProperties);
Map<String, String> values = new HashMap<>();
sessionValue.setValues(values);
sessionStruct.setValues(sessionValue);
return sessionStruct;
}
@Override
@UserBtRegisterFill
public void persistSession(String token, SessionValue sessionValue) {
Timestamp current = new Timestamp(System.currentTimeMillis());
sessionValue.setLastAccessTime(current);
String json = JSON.toJSONString(sessionValue);
stringRedisTemplate.opsForValue().set(Constants.Session.USER_SESSION_CACHE + token, json,
Constants.Session.ONE_DAY, TimeUnit.SECONDS);
String key = generateLoginPropertiesKey(sessionValue.getUser().getId(), sessionValue.getLoginProperties());
stringRedisTemplate.opsForValue().set(key, token, Constants.Session.ONE_DAY, TimeUnit.SECONDS);
setUserIdTokenKeys(sessionValue.getUser().getId(), key);
} }
}
/**
@Override * 设置用户token集合方便注销使用
public String findSessionValueBySessionId(String sessionId) { *
String result = stringRedisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + sessionId); * @param userId
return StringUtils.defaultString(result, ""); * @param key
} */
private void setUserIdTokenKeys(long userId, String key) {
@Override if (0L != userId) {
public SessionStruct newSession(User user, LoginProperties loginProperties) { try {
Timestamp now = new Timestamp(System.currentTimeMillis()); stringRedisTemplate.opsForSet().add(Constants.Session.USER_SESSION_KEY_SET + userId, key);
SessionStruct sessionStruct = new SessionStruct(); stringRedisTemplate.expire(Constants.Session.USER_SESSION_KEY_SET + userId, Constants.Session.ONE_DAY, TimeUnit.SECONDS);
SessionValue sessionValue = new SessionValue(); } catch (Exception e) {
sessionStruct.setSid(UUID.randomUUID().toString()); log.error("存储用户注销件失败,userId:{},Exception:{}", userId, e);
sessionValue.setCreatedAt(now); }
sessionValue.setLastAccessTime(now);
sessionValue.setUser(user); }
sessionValue.setLoginProperties(loginProperties);
Map<String, String> values = new HashMap<>();
sessionValue.setValues(values);
sessionStruct.setValues(sessionValue);
return sessionStruct;
}
@Override
@UserBtRegisterFill
public void persistSession(String token, SessionValue sessionValue) {
Timestamp current = new Timestamp(System.currentTimeMillis());
sessionValue.setLastAccessTime(current);
String json = JSON.toJSONString(sessionValue);
stringRedisTemplate.opsForValue().set(Constants.Session.USER_SESSION_CACHE + token, json,
Constants.Session.ONE_DAY, TimeUnit.SECONDS);
String key = generateLoginPropertiesKey(sessionValue.getUser().getId(), sessionValue.getLoginProperties());
stringRedisTemplate.opsForValue().set(key, token, Constants.Session.ONE_DAY, TimeUnit.SECONDS);
setUserIdTokenKeys(sessionValue, key);
}
/**
* 设置用户token集合方便注销使用
* @param sessionValue
* @param key
*/
private void setUserIdTokenKeys(SessionValue sessionValue, String key) {
String useIdKeys = stringRedisTemplate.opsForValue().get(Constants.Session.USER_SESSION_KEY_SET + sessionValue.getUser().getId());
Set useIdKeySet = null;
if (StringUtils.isNotEmpty(useIdKeys)) {
useIdKeySet = JSON.parseObject(useIdKeys, Set.class);
} else {
useIdKeySet = new HashSet();
}
useIdKeySet.add(key);
stringRedisTemplate.opsForValue().set(Constants.Session.USER_SESSION_KEY_SET + sessionValue.getUser().getId(), JSONObject.toJSONString(useIdKeySet), Constants.Session.ONE_DAY, TimeUnit.SECONDS);
}
@Override
public SessionStruct findSessionBySessionId(String sessionId) {
String sessionValue = findSessionValueBySessionId(sessionId);
if (StringUtils.isEmpty(sessionValue)) {
return null;
} }
try {
SessionValue value = JSON.parseObject(sessionValue, SessionValue.class);
if (null == value) { @Override
return null; public SessionStruct findSessionBySessionId(String sessionId) {
} String sessionValue = findSessionValueBySessionId(sessionId);
SessionStruct struct = new SessionStruct(); if (StringUtils.isEmpty(sessionValue)) {
struct.setSid(sessionId); return null;
struct.setValues(value); }
return struct; try {
} catch (Exception ex) { SessionValue value = JSON.parseObject(sessionValue, SessionValue.class);
return null; if (null == value) {
return null;
}
SessionStruct struct = new SessionStruct();
struct.setSid(sessionId);
struct.setValues(value);
return struct;
} catch (Exception ex) {
return null;
}
} }
} @Override
public void deleteByUserId(long userId) {
@Override
public void deleteByUserId(long userId) { Set useIdKeys = stringRedisTemplate.opsForSet().members(Constants.Session.USER_SESSION_KEY_SET + userId);
// String pattern = Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":*"; if (!CollectionUtils.isEmpty(useIdKeys)) {
// Set<String> keys = stringRedisTemplate.keys(pattern); useIdKeys.forEach(key -> {
// if (!CollectionUtils.isEmpty(keys)) { stringRedisTemplate.delete(String.valueOf(key));
// log.info("删除用户userId={}的缓存信息,个数:{},keys={}", userId, });
// keys.size(), }
// Joiner.on(",").join(keys));
// } }
String useIdKeys = stringRedisTemplate.opsForValue().get(Constants.Session.USER_SESSION_KEY_SET + userId);
if (StringUtils.isNotEmpty(useIdKeys)) {
Set useIdKeySet = JSON.parseObject(useIdKeys, Set.class);
useIdKeySet.forEach(key -> {
stringRedisTemplate.delete(String.valueOf(key));
});
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment