Merge remote-tracking branch 'origin/在线访问lhj' into 在线访问lhj

在线访问lhj
李宏杰 8 months ago
commit def8cad9d6

@ -14,19 +14,23 @@ import redis.clients.jedis.ShardedJedis;
/** /**
* *
* *
*/ */
@Service("cacheService") @Service("cacheService")
public class CacheService { public class CacheService {
// 定义 Redis 键的前缀
private final static String REDIS_PRE_KEY = "TAMGUO:"; private final static String REDIS_PRE_KEY = "TAMGUO:";
// 创建对象序列化工具
private SerializeTranscoder objectSerialize = new ObjectUtil(); private SerializeTranscoder objectSerialize = new ObjectUtil();
@Autowired @Autowired
private RedisXMLConfigure redisXMLConfigure; private RedisXMLConfigure redisXMLConfigure;
/** /**
* *
* @Title: get @Description: @param @return String @throws *
* @param key
* @return
*/ */
public String get(String key) { public String get(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -40,8 +44,10 @@ public class CacheService {
} }
/** /**
* *
* @Title: set @Description: @param @return void @throws *
* @param key
* @param value
*/ */
public void set(String key, String value) { public void set(String key, String value) {
key = getPreKey(key); key = getPreKey(key);
@ -55,16 +61,11 @@ public class CacheService {
} }
/** /**
* *
* set *
* * @param key
* @param key * @param value
* @param value * @param time
* @param time
*
* @description
* @exception @since
* 1.0.0
*/ */
public void set(String key, String value, int time) { public void set(String key, String value, int time) {
key = getPreKey(key); key = getPreKey(key);
@ -79,10 +80,10 @@ public class CacheService {
} }
/** /**
* redis * Redis
* *
* @param key key * @param key
* @param value * @param value
*/ */
public void setObject(String key, Object value) { public void setObject(String key, Object value) {
key = getPreKey(key); key = getPreKey(key);
@ -93,16 +94,16 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
} }
/** /**
* * Redis
* *
* @param key key * @param key
* @param value * @param value
* @param time * @param time
*/ */
public void setObject(String key, Object value, int time) { public void setObject(String key, Object value, int time) {
key = getPreKey(key); key = getPreKey(key);
@ -113,15 +114,15 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
} }
/** /**
* * Redis
* *
* @param key key * @param key
* @return * @return
*/ */
public Object getObject(String key) { public Object getObject(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -141,10 +142,10 @@ public class CacheService {
} }
/** /**
* * Redis
* *
* @param key key * @param key
* @return * @return
*/ */
public boolean deleteObject(String key) { public boolean deleteObject(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -155,15 +156,16 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
return false; return false;
} }
/** /**
* *
* @Title: isExist @Description: key @param @return boolean *
* @throws * @param key
* @return
*/ */
public boolean isExist(String key) { public boolean isExist(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -179,10 +181,22 @@ public class CacheService {
return false; return false;
} }
/**
*
*
* @param key
* @return
*/
public boolean notExist(String key) { public boolean notExist(String key) {
return !isExist(key); return!isExist(key);
} }
/**
*
*
* @param key
* @return
*/
public boolean delete(String key) { public boolean delete(String key) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -198,11 +212,11 @@ public class CacheService {
} }
/** /**
* redis list value key () *
* *
* @param key * @param key
* @param value * @param value
* @return * @return
*/ */
public long putToListEnd(String key, String value) { public long putToListEnd(String key, String value) {
key = getPreKey(key); key = getPreKey(key);
@ -217,28 +231,25 @@ public class CacheService {
} }
/** /**
* valuekey, *
* *
* @author zhangxin * @param key
* @param key * @param value
* @param value * @param seconds
* @param seconds * @param score
* @param score * @return
* @return long
*/ */
public long addToSortedSetAndExpire(String key, String value, int seconds, double score) { public long addToSortedSetAndExpire(String key, String value, int seconds, double score) {
return addToSortedSet(key, value, seconds, true, score); return addToSortedSet(key, value, seconds, true, score);
} }
/** /**
* valuekey valuescore *
* *
* @author zhangxin * @param key
* @param key * @param value
* @param value * @param score
* @param score * @return
* @return long
*/ */
public double addToSortedSetScore(String key, String value, double score) { public double addToSortedSetScore(String key, String value, double score) {
key = getPreKey(key); key = getPreKey(key);
@ -248,47 +259,28 @@ public class CacheService {
Double zincrby = conn.zincrby(key, score, value); Double zincrby = conn.zincrby(key, score, value);
return zincrby; return zincrby;
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
}
}
/**
* memberScore
* @param key
* @param value
* @return
*/
public Double getMemberScore(String key, String member) {
key = getPreKey(key);
ShardedJedis conn = null;
try {
conn = redisXMLConfigure.getConnection();
Double zscore = conn.zscore(key, member);
return zscore == null ? 0 : zscore;
} finally {
redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* valuekey, *
* *
* @author zhangxin * @param key
* @param key * @param value
* @param value * @param score
* @param score * @return
* @return long
*/ */
public long addToSortedSet(String key, String value, double score) { public long addToSortedSet(String key, String value, double score) {
return addToSortedSet(key, value, -1, false, score); return addToSortedSet(key, value, -1, false, score);
} }
/** /**
* member *
* *
* @return isExist true * @param key
* @param member
* @return
*/ */
public boolean isExistSortedSet(String key, String member) { public boolean isExistSortedSet(String key, String member) {
key = getPreKey(key); key = getPreKey(key);
@ -296,16 +288,18 @@ public class CacheService {
try { try {
conn = redisXMLConfigure.getConnection(); conn = redisXMLConfigure.getConnection();
Long zrank = conn.zrank(key, member); Long zrank = conn.zrank(key, member);
return zrank != null; return zrank!= null;
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
} }
/** /**
* member *
* *
* @return isExist true * @param key
* @param member
* @return
*/ */
public boolean delSortedSetMember(String key, String[] member) { public boolean delSortedSetMember(String key, String[] member) {
key = getPreKey(key); key = getPreKey(key);
@ -320,9 +314,14 @@ public class CacheService {
} }
/** /**
* valuekey, setExpirefalse, seconds *
* *
* @return * @param key
* @param value
* @param seconds
* @param setExpire
* @param score
* @return
*/ */
private long addToSortedSet(String key, String value, int seconds, boolean setExpire, double score) { private long addToSortedSet(String key, String value, int seconds, boolean setExpire, double score) {
key = getPreKey(key); key = getPreKey(key);
@ -335,19 +334,17 @@ public class CacheService {
} }
return addNum; return addNum;
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
} }
/** /**
* score *
* *
* @author zhangxin * @param key
* @param key * @param pageNo 1
* @param pageNo * @param pageSize
* 1 * @return
* @param pageSize
* @return Set<String>
*/ */
public Set<String> getSortedSetByPage(String key, int pageNo, int pageSize) { public Set<String> getSortedSetByPage(String key, int pageNo, int pageSize) {
key = getPreKey(key); key = getPreKey(key);
@ -365,11 +362,17 @@ public class CacheService {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
return null; return null;
} }
/**
*
*
* @param key
* @return
*/
public List<String> getListHead(String key) { public List<String> getListHead(String key) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -386,12 +389,12 @@ public class CacheService {
} }
/** /**
* map * Map Redis
* *
* @param key * @param key
* @param field map field * @param field Map
* @param value map value * @param value Map
* @return if filed exist return 0 else return 1 * @return 0 1
*/ */
public Long hset(String key, String field, String value) { public Long hset(String key, String field, String value) {
key = getPreKey(key); key = getPreKey(key);
@ -400,10 +403,17 @@ public class CacheService {
conn = redisXMLConfigure.getConnection(); conn = redisXMLConfigure.getConnection();
return conn.hset(key, field, value); return conn.hset(key, field, value);
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
} }
/**
* Map Redis
*
* @param key
* @param values Map
* @return
*/
public String hset(String key, Map<String, String> values) { public String hset(String key, Map<String, String> values) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -411,10 +421,18 @@ public class CacheService {
conn = redisXMLConfigure.getConnection(); conn = redisXMLConfigure.getConnection();
return conn.hmset(key, values); return conn.hmset(key, values);
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
} }
/**
* Map Redis
*
* @param key
* @param values Map
* @param time
* @return
*/
public String hset(String key, Map<String, String> values, int time) { public String hset(String key, Map<String, String> values, int time) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
@ -429,28 +447,28 @@ public class CacheService {
} }
/** /**
* mapfield * Map
* *
* @param key * @param key
* @param field map field * @param field
* @return * @return
*/ */
public String hget(String key, String field) { public String hget(String key, String field) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
try { try {
conn = redisXMLConfigure.getConnection(); conn = redisXML Configure.getConnection();
return conn.hget(key, field); return conn.hget(key, field);
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXML Configure.closeConnection(conn);
} }
} }
/** /**
* keystring1 * key 1
* *
* @param key * @param key
* @return * @return 1
*/ */
public Long decr(String key) { public Long decr(String key) {
key = getPreKey(key); key = getPreKey(key);
@ -462,24 +480,30 @@ public class CacheService {
redisXMLConfigure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/** /**
* keystring1 * key 1
* *
* @param key * @param key
* @return * @return 1
*/ */
public Long incr(String key) { public Long incr(String key) {
key = getPreKey(key); key = getPreKey(key);
ShardedJedis conn = null; ShardedJedis conn = null;
try { try {
conn = redisXMLConfigure.getConnection(); conn = redisXML Configure.getConnection();
return conn.incr(key); return conn.incr(key);
} finally { } finally {
redisXMLConfigure.closeConnection(conn); redisXMLConfigure.closeConnection(conn);
} }
} }
/**
* Redis
*
* @param key
* @return
*/
private String getPreKey(String key) { private String getPreKey(String key) {
String temp_pre = redisXMLConfigure.getPreKey(); String temp_pre = redisXMLConfigure.getPreKey();
if (null == temp_pre) { if (null == temp_pre) {
@ -487,5 +511,4 @@ public class CacheService {
} }
return temp_pre + key; return temp_pre + key;
} }
}
}

@ -1,13 +1,28 @@
package com.tamguo.config.redis; package com.tamguo.config.redis;
/**
* PoolConfigBean Redis
*/
public class PoolConfigBean { public class PoolConfigBean {
// 最大活跃连接数
private int max_active; private int max_active;
// 最大空闲连接数
private int max_idle; private int max_idle;
// 最大等待时间(毫秒)
private long max_wait; private long max_wait;
/**
*
*/
public PoolConfigBean() { public PoolConfigBean() {
} }
/**
*
* @param max_active
* @param max_idle
* @param max_wait
*/
public PoolConfigBean(int max_active, int max_idle, long max_wait) { public PoolConfigBean(int max_active, int max_idle, long max_wait) {
super(); super();
this.max_active = max_active; this.max_active = max_active;
@ -15,33 +30,60 @@ public class PoolConfigBean {
this.max_wait = max_wait; this.max_wait = max_wait;
} }
/**
*
* @return
*/
public int getMax_active() { public int getMax_active() {
return max_active; return max_active;
} }
/**
*
* @param max_active
*/
public void setMax_active(int max_active) { public void setMax_active(int max_active) {
this.max_active = max_active; this.max_active = max_active;
} }
/**
*
* @return
*/
public int getMax_idle() { public int getMax_idle() {
return max_idle; return max_idle;
} }
/**
*
* @param max_idle
*/
public void setMax_idle(int max_idle) { public void setMax_idle(int max_idle) {
this.max_idle = max_idle; this.max_idle = max_idle;
} }
/**
*
* @return
*/
public long getMax_wait() { public long getMax_wait() {
return max_wait; return max_wait;
} }
/**
*
* @param max_wait
*/
public void setMax_wait(long max_wait) { public void setMax_wait(long max_wait) {
this.max_wait = max_wait; this.max_wait = max_wait;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return "PoolConfig [max_active=" + max_active + ", max_idle=" + max_idle + ", max_wait=" + max_wait + "]"; return "PoolConfig [max_active=" + max_active + ", max_idle=" + max_idle + ", max_wait=" + max_wait + "]";
} }
}
}

@ -1,11 +1,26 @@
package com.tamguo.config.redis; package com.tamguo.config.redis;
/**
* RedisServerNodeBean Redis
*/
public class RedisServerNodeBean { public class RedisServerNodeBean {
// Redis 服务器的 IP 地址
private String ip; private String ip;
// Redis 服务器的端口号
private int port; private int port;
// 是否需要身份验证
private boolean needAuth; private boolean needAuth;
// 身份验证密码
private String auth; private String auth;
/**
* RedisServerNodeBean
*
* @param ip Redis IP
* @param port Redis
* @param needAuth
* @param auth
*/
public RedisServerNodeBean(String ip, int port, boolean needAuth, String auth) { public RedisServerNodeBean(String ip, int port, boolean needAuth, String auth) {
this.ip = ip; this.ip = ip;
this.port = port; this.port = port;
@ -13,41 +28,85 @@ public class RedisServerNodeBean {
this.auth = auth; this.auth = auth;
} }
/**
* Redis IP
*
* @return Redis IP
*/
public String getIp() { public String getIp() {
return ip; return ip;
} }
/**
* Redis IP
*
* @param ip Redis IP
*/
public void setIp(String ip) { public void setIp(String ip) {
this.ip = ip; this.ip = ip;
} }
/**
* Redis
*
* @return Redis
*/
public int getPort() { public int getPort() {
return port; return port;
} }
/**
* Redis
*
* @param port Redis
*/
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
/**
*
*
* @return
*/
public boolean isNeedAuth() { public boolean isNeedAuth() {
return needAuth; return needAuth;
} }
/**
*
*
* @param needAuth
*/
public void setNeedAuth(boolean needAuth) { public void setNeedAuth(boolean needAuth) {
this.needAuth = needAuth; this.needAuth = needAuth;
} }
/**
*
*
* @return
*/
public String getAuth() { public String getAuth() {
return auth; return auth;
} }
/**
*
*
* @param auth
*/
public void setAuth(String auth) { public void setAuth(String auth) {
this.auth = auth; this.auth = auth;
} }
/**
* toString RedisServerNodeBean
*
* @return RedisServerNodeBean
*/
@Override @Override
public String toString() { public String toString() {
return "RedisServer [ip=" + ip + ", port=" + port + ", needAuth=" + needAuth + ", auth=" + auth + "]"; return "RedisServer [ip=" + ip + ", port=" + port + ", needAuth=" + needAuth + ", auth=" + auth + "]";
} }
}
}

@ -18,158 +18,187 @@ import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool; import redis.clients.jedis.ShardedJedisPool;
/**
* RedisXMLConfigure XML Redis ShardedJedisPool
*/
@Component("redisConfigure") @Component("redisConfigure")
public class RedisXMLConfigure implements InitializingBean { public class RedisXMLConfigure implements InitializingBean {
private static final Logger logger = Logger.getLogger(RedisXMLConfigure.class); private static final Logger logger = Logger.getLogger(RedisXMLConfigure.class); // 日志记录器
private static String preKey; private static String preKey; // Redis 键的前缀
private static Document document = null; private static Document document = null; // XML 文档对象
private ShardedJedisPool shardedJedisPool; private ShardedJedisPool shardedJedisPool; // ShardedJedis 连接池
/**
*
* XML Redis ShardedJedisPool
* @throws Exception
*/
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
XMLConfiguration xmlConfiguration = new XMLConfiguration(); XMLConfiguration xmlConfiguration = new XMLConfiguration(); // 创建 XML 配置对象
String REDIS_PATH = "redis.xml"; String REDIS_PATH = "redis.xml"; // XML 配置文件路径
InputStream stream = null; InputStream stream = null; // 输入流对象
try { try {
stream = this.getClass().getClassLoader().getResourceAsStream(REDIS_PATH); stream = this.getClass().getClassLoader().getResourceAsStream(REDIS_PATH); // 获取 XML 配置文件的输入流
if (stream == null) { if (stream == null) { // 如果输入流为空
logger.error("load redis.xml failed!!!" + REDIS_PATH); logger.error("load redis.xml failed!!!" + REDIS_PATH); // 记录错误日志
throw new RuntimeException("load redis.xml failed"); throw new RuntimeException("load redis.xml failed"); // 抛出运行时异常
} }
logger.info("Redis XML config path:" + REDIS_PATH); logger.info("Redis XML config path:" + REDIS_PATH); // 记录日志
if (xmlConfiguration.readConfigFile(stream)) { if (xmlConfiguration.readConfigFile(stream)) { // 如果成功读取 XML 配置文件
document = xmlConfiguration.getDocument(); document = xmlConfiguration.getDocument(); // 获取 XML 文档对象
} else { } else {
logger.error("load redis.xml failed!!!"); logger.error("load redis.xml failed!!!"); // 记录错误日志
} }
} finally { } finally {
if (null != stream) if (null!= stream) // 如果输入流不为空
stream.close(); stream.close(); // 关闭输入流
} }
//初始化参数
initPreKey(); // 初始化参数
PoolConfigBean pcb = initPoolConfigBean(); initPreKey(); // 初始化 Redis 键的前缀
List<RedisServerNodeBean> rsnbs = initRedisServerNodeBeans(); PoolConfigBean pcb = initPoolConfigBean(); // 初始化连接池配置对象
//实现shardedJedisPool List<RedisServerNodeBean> rsnbs = initRedisServerNodeBeans(); // 初始化 Redis 服务器节点信息列表
// 创建 JedisPoolConfig 对象
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//no maxActive config // 设置最大空闲连接数
jedisPoolConfig.setMaxIdle(pcb.getMax_idle()); jedisPoolConfig.setMaxIdle(pcb.getMax_idle());
// 设置最大等待时间(毫秒)
jedisPoolConfig.setMaxWaitMillis(pcb.getMax_wait()); jedisPoolConfig.setMaxWaitMillis(pcb.getMax_wait());
shardedJedisPool = new ShardedJedisPool(jedisPoolConfig,getJedisShardInfo(rsnbs)); // 创建 ShardedJedisPool 对象
if(shardedJedisPool == null){ shardedJedisPool = new ShardedJedisPool(jedisPoolConfig, getJedisShardInfo(rsnbs));
throw new RuntimeException("config redis.xml error"); if (shardedJedisPool == null) { // 如果 ShardedJedisPool 对象为空
throw new RuntimeException("config redis.xml error"); // 抛出运行时异常
} }
} }
/** /**
* jedis *
* @return
*/ */
private PoolConfigBean initPoolConfigBean() { private PoolConfigBean initPoolConfigBean() {
PoolConfigBean poolConfigBean = new PoolConfigBean(); PoolConfigBean poolConfigBean = new PoolConfigBean(); // 创建连接池配置对象
Element poolElement = (Element) document.getElementsByTagName("pool").item(0); Element poolElement = (Element) document.getElementsByTagName("pool").item(0); // 获取 pool 元素
int max_active = poolElement.hasAttribute("maxActive") ? Integer.parseInt(poolElement.getAttribute("maxActive")) : -1;
int max_idle = poolElement.hasAttribute("maxIdle") ? Integer.parseInt(poolElement.getAttribute("maxIdle")) : -1; int max_active = poolElement.hasAttribute("maxActive")? Integer.parseInt(poolElement.getAttribute("maxActive")) : -1; // 获取最大活跃连接数
long max_wait = poolElement.hasAttribute("maxWait") ? Long.parseLong(poolElement.getAttribute("maxWait")) : -1; int max_idle = poolElement.hasAttribute("maxIdle")? Integer.parseInt(poolElement.getAttribute("maxIdle")) : -1; // 获取最大空闲连接数
poolConfigBean.setMax_active(max_active); long max_wait = poolElement.hasAttribute("maxWait")? Long.parseLong(poolElement.getAttribute("maxWait")) : -1; // 获取最大等待时间(毫秒)
poolConfigBean.setMax_idle(max_idle);
poolConfigBean.setMax_wait(max_wait); poolConfigBean.setMax_active(max_active); // 设置最大活跃连接数
poolConfigBean.setMax_idle(max_idle); // 设置最大空闲连接数
poolConfigBean.setMax_wait(max_wait); // 设置最大等待时间(毫秒)
return poolConfigBean; return poolConfigBean;
} }
/** /**
* redisserver * Redis
* @return Redis
*/ */
private List<RedisServerNodeBean> initRedisServerNodeBeans() { private List<RedisServerNodeBean> initRedisServerNodeBeans() {
List<RedisServerNodeBean> redisServers = new ArrayList<RedisServerNodeBean>(); List<RedisServerNodeBean> redisServers = new ArrayList<RedisServerNodeBean>(); // 创建 Redis 服务器节点信息列表
NodeList serverElements = document.getElementsByTagName("server");
int serverLen = serverElements.getLength(); NodeList serverElements = document.getElementsByTagName("server"); // 获取所有 server 元素
if (serverLen < 1) { int serverLen = serverElements.getLength(); // 获取 server 元素的数量
logger.error("redis.servers.server must have one !");
return null; if (serverLen < 1) { // 如果 server 元素的数量小于 1
logger.error("redis.servers.server must have one!"); // 记录错误日志
return null; // 返回空列表
} }
for (int i = 0; i < serverLen; i++) {
Element serverElement = (Element) serverElements.item(i); for (int i = 0; i < serverLen; i++) { // 遍历所有 server 元素
String temp_ip = serverElement.hasAttribute("ip") ? serverElement.getAttribute("ip") : null; Element serverElement = (Element) serverElements.item(i); // 获取当前 server 元素
if (temp_ip == null) {
logger.error("redis.servers.server.ip must be supplied!"); String temp_ip = serverElement.hasAttribute("ip")? serverElement.getAttribute("ip") : null; // 获取 IP 地址
return null; if (temp_ip == null) { // 如果 IP 地址为空
logger.error("redis.servers.server.ip must be supplied!"); // 记录错误日志
return null; // 返回空列表
} }
String temp_port = serverElement.hasAttribute("port") ? serverElement.getAttribute("port") : "6379"; String temp_port = serverElement.hasAttribute("port")? serverElement.getAttribute("port") : "6379"; // 获取端口号
String temp_needAuth = serverElement.hasAttribute("needAuth") ? serverElement.getAttribute("needAuth") : "false"; String temp_needAuth = serverElement.hasAttribute("needAuth")? serverElement.getAttribute("needAuth") : "false"; // 获取是否需要身份验证
String temp_auth = null; String temp_auth = null; // 身份验证密码
// need auth
// 需要身份验证
if ("true".equals(temp_needAuth)) { if ("true".equals(temp_needAuth)) {
temp_auth = serverElement.hasAttribute("auth") ? serverElement.getAttribute("auth") : null; temp_auth = serverElement.hasAttribute("auth")? serverElement.getAttribute("auth") : null; // 获取身份验证密码
if (null == temp_auth) { if (null == temp_auth) { // 如果身份验证密码为空
logger.error("since needAuth is true,auth must be supplied!"); logger.error("since needAuth is true, auth must be supplied!"); // 记录错误日志
return null; return null; // 返回空列表
} }
} }
RedisServerNodeBean rs = null; RedisServerNodeBean rs = null; // 创建 Redis 服务器节点对象
try { try {
rs = new RedisServerNodeBean(temp_ip, Integer.parseInt(temp_port), Boolean.parseBoolean(temp_needAuth), temp_auth); rs = new RedisServerNodeBean(temp_ip, Integer.parseInt(temp_port), Boolean.parseBoolean(temp_needAuth), temp_auth); // 创建 Redis 服务器节点对象
} catch (NumberFormatException e) { } catch (NumberFormatException e) { // 如果端口号转换为整数时发生异常
logger.error("port must be a number!\n" + e.getMessage()); logger.error("port must be a number!\n" + e.getMessage()); // 记录错误日志
return null; return null; // 返回空列表
} }
redisServers.add(rs); redisServers.add(rs); // 将 Redis 服务器节点对象添加到列表中
} }
return redisServers; return redisServers;
} }
/** /**
* JedisShardInfo * JedisShardInfo
* @param redisServers * @param redisServers Redis
* @return * @return JedisShardInfo
*/ */
private List<JedisShardInfo> getJedisShardInfo(List<RedisServerNodeBean> redisServers) { private List<JedisShardInfo> getJedisShardInfo(List<RedisServerNodeBean> redisServers) {
if(redisServers == null){ if (redisServers == null) { // 如果 Redis 服务器节点信息列表为空
logger.error("redisServers must not be empty null"); logger.error("redisServers must not be empty null"); // 记录错误日志
return null; return null; // 返回空列表
} }
int serverLen = redisServers.size(); int serverLen = redisServers.size(); // 获取 Redis 服务器节点的数量
if (serverLen < 1) { if (serverLen < 1) { // 如果 Redis 服务器节点的数量小于 1
logger.error("redisServers must not be empty "); logger.error("redisServers must not be empty "); // 记录错误日志
return null; return null; // 返回空列表
} }
List<JedisShardInfo> servers = new ArrayList<JedisShardInfo>(serverLen); List<JedisShardInfo> servers = new ArrayList<JedisShardInfo>(serverLen); // 创建 JedisShardInfo 对象列表
for (int i = 0; i < serverLen; i++) {
RedisServerNodeBean redisServer = redisServers.get(i); for (int i = 0; i < serverLen; i++) { // 遍历 Redis 服务器节点信息列表
JedisShardInfo jedisShardInfo = new JedisShardInfo(redisServer.getIp(), redisServer.getPort()); RedisServerNodeBean redisServer = redisServers.get(i); // 获取当前 Redis 服务器节点对象
if (redisServer.isNeedAuth()) { JedisShardInfo jedisShardInfo = new JedisShardInfo(redisServer.getIp(), redisServer.getPort()); // 创建 JedisShardInfo 对象
jedisShardInfo.setPassword(redisServer.getAuth()); if (redisServer.isNeedAuth()) { // 如果需要身份验证
jedisShardInfo.setPassword(redisServer.getAuth()); // 设置身份验证密码
} }
servers.add(jedisShardInfo); servers.add(jedisShardInfo); // 将 JedisShardInfo 对象添加到列表中
} }
return servers; return servers;
} }
/* /**
* rediskey * Redis
*/ */
private void initPreKey() { private void initPreKey() {
Element preKeyElement = (Element) document.getElementsByTagName("preKey").item(0); Element preKeyElement = (Element) document.getElementsByTagName("preKey").item(0); // 获取 preKey 元素
preKey = preKeyElement.hasAttribute("value") ? preKeyElement.getAttribute("value") : ""; preKey = preKeyElement.hasAttribute("value")? preKeyElement.getAttribute("value") : ""; // 获取前缀值
} }
/**
* Redis
* @return Redis
*/
public String getPreKey() { public String getPreKey() {
return preKey; return preKey;
} }
/** /**
* jedis * Jedis
* @return * @return Jedis
*/ */
public ShardedJedis getConnection() { public ShardedJedis getConnection() {
return shardedJedisPool.getResource(); return shardedJedisPool.getResource();
} }
/** /**
* jedis * Jedis
* @param resource * @param resource Jedis
*/ */
public void closeConnection(ShardedJedis resource) { public void closeConnection(ShardedJedis resource) {
resource.close(); resource.close();
} }
}
}

@ -8,31 +8,35 @@ import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data; import lombok.Data;
/**
* BookCategoryEntity
*/
@Data @Data
@TableName(value="b_book_category") @TableName(value="b_book_category")
public class BookCategoryEntity extends Model<BookCategoryEntity>{ public class BookCategoryEntity extends Model<BookCategoryEntity> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 定义字段
@TableId @TableId
private String id; private String id; // 分类 ID
private String parentId; private String parentId; // 父分类 ID
private String parentIds; private String parentIds; // 父分类 ID 列表
private String treeSort; private String treeSort; // 树排序
private String treeSorts; private String treeSorts; // 树排序列表
private String treeLeaf; private String treeLeaf; // 是否叶子节点
private String treeLevel; private String treeLevel; // 树层次
private String treeNames; private String treeNames; // 树名称
private String name; private String name; // 分类名称
private String seoTitle; private String seoTitle; // SEO 标题
private String seoKeywords; private String seoKeywords; // SEO 关键词
private String seoDescription; private String seoDescription; // SEO 描述
private Date createDate; private Date createDate; // 创建日期
private Date updateDate; private Date updateDate; // 更新日期
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
}
}

@ -10,33 +10,39 @@ import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data; import lombok.Data;
/**
* BookEntity
*/
@Data @Data
@TableName(value="b_book") @TableName(value="b_book")
public class BookEntity extends Model<BookEntity>{ public class BookEntity extends Model<BookEntity> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 定义字段
@TableId @TableId
private String id; private String id; // 书籍 ID
private String categoryId; private String categoryId; // 书籍分类 ID
private String bookImage; private String bookImage; // 书籍图片
private String owner; private String owner; // 书籍所有者
private String name; private String name; // 书籍名称
private String seoTitle; private String seoTitle; // SEO 标题
private String seoKeywords; private String seoKeywords; // SEO 关键词
private String seoDescription; private String seoDescription; // SEO 描述
private Date createDate; private Date createDate; // 创建日期
private Date updateDate; private Date updateDate; // 更新日期
// 定义关联字段
@TableField(exist=false) @TableField(exist=false)
private List<String> categoryIds; private List<String> categoryIds; // 分类 ID 列表
@TableField(exist=false) @TableField(exist=false)
private String memberName; private String memberName; // 会员名称
@TableField(exist=false) @TableField(exist=false)
private String categoryName; private String categoryName; // 分类名称
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
} }

@ -13,46 +13,51 @@ import com.baomidou.mybatisplus.annotations.TableName;
import com.tamguo.modules.book.model.enums.DocumentStatusEnum; import com.tamguo.modules.book.model.enums.DocumentStatusEnum;
import lombok.Data; import lombok.Data;
/**
* DocumentEntity
*/
@Data @Data
@TableName(value="b_document") @TableName(value="b_document")
public class DocumentEntity extends Model<DocumentEntity>{ public class DocumentEntity extends Model<DocumentEntity> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 定义字段
@TableId @TableId
private String id; private String id; // 文档 ID
private String batchNo; private String batchNo; // 批次号
private String parentId; private String parentId; // 父文档 ID
private String bookId; private String bookId; // 所属书籍 ID
private String owner; private String owner; // 所有者
private String name; private String name; // 文档名称
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString) @JSONField(serialzeFeatures=SerializerFeature.WriteEnumUsingToString)
private DocumentStatusEnum status; private DocumentStatusEnum status; // 文档状态
@TableField(value="is_open") @TableField(value="is_open")
private String isOpen; private String isOpen; // 是否公开
private Date createDate; private Date createDate; // 创建日期
private Date updateDate; private Date updateDate; // 更新日期
private String content; // 定义关联字段
private String markdown; private String content; // 文档内容
private String markdown; // Markdown 内容
@TableField(exist=false) @TableField(exist=false)
private Integer level; private Integer level; // 层级
@TableField(exist=false) @TableField(exist=false)
private String rootId; private String rootId; // 根文档 ID
@TableField(exist=false) @TableField(exist=false)
private boolean leaf; private boolean leaf; // 是否叶子节点
@TableField(exist=false) @TableField(exist=false)
private List<DocumentEntity> children; private List<DocumentEntity> children; // 子文档列表
@TableField(exist=false) @TableField(exist=false)
private String cover; private String cover; // 封面
@TableField(exist=false) @TableField(exist=false)
private List<FileUploadEntity> fileUploads; private List<FileUploadEntity> fileUploads; // 文件上传列表
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
}
}

@ -4,16 +4,29 @@ import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data; import lombok.Data;
/**
* FileEntity
*/
@Data @Data
@TableName(value="b_file_entity") @TableName(value="b_file_entity")
public class FileEntity { public class FileEntity {
@TableId("file_id") // 文件 ID
@TableId("file_id")
private String fileId; private String fileId;
// 文件 MD5 值
private String fileMd5; private String fileMd5;
// 文件路径
private String filePath; private String filePath;
// 文件类型
private String fileContentType; private String fileContentType;
// 文件扩展名
private String fileExtension; private String fileExtension;
// 文件大小(字节数)
private Long fileSize; private Long fileSize;
} }

@ -12,33 +12,51 @@ import com.tamguo.modules.book.model.enums.BizTypeEnum;
import com.tamguo.modules.book.model.enums.FileUploadStatusEnum; import com.tamguo.modules.book.model.enums.FileUploadStatusEnum;
import lombok.Data; import lombok.Data;
/**
* FileUploadEntity
*/
@Data @Data
@TableName(value="b_file_upload") @TableName(value="b_file_upload")
public class FileUploadEntity extends Model<FileUploadEntity>{ public class FileUploadEntity extends Model<FileUploadEntity> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 文件上传 ID
private String id; private String id;
// 文件 ID
private String fileId; private String fileId;
// 文件名
private String fileName; private String fileName;
// 文件类型
private String fileType; private String fileType;
private String bizKey; // 业务键
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString) private String bizKey;
// 业务类型
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private BizTypeEnum bizType; private BizTypeEnum bizType;
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString) // 文件上传状态
@JSONField(serialzeFeatures = SerializerFeature.WriteEnumUsingToString)
private FileUploadStatusEnum status; private FileUploadStatusEnum status;
// 创建人
private String createBy; private String createBy;
// 创建日期
private Date createDate; private Date createDate;
// 更新人
private String updateBy; private String updateBy;
// 更新日期
private Date updateDate; private Date updateDate;
// 备注
private String remarks; private String remarks;
// 文件路径(不存在数据库中,通过查询关联表得到)
@TableField(exist=false) @TableField(exist=false)
private String filePath; private String filePath;
// 文件大小(字节数)(不存在数据库中,通过查询关联表得到)
@TableField(exist=false) @TableField(exist=false)
private Long fileSize; private Long fileSize;
// 重写 pkVal 方法,返回 ID 作为主键值
@Override @Override
protected Serializable pkVal() { protected Serializable pkVal() {
return getId(); return getId();
} }
}
}

@ -1,32 +1,50 @@
package com.tamguo.modules.book.model.enums; package com.tamguo.modules.book.model.enums;
import java.io.Serializable; import java.io.Serializable; // 导入 Serializable 接口
import com.baomidou.mybatisplus.enums.IEnum; import com.baomidou.mybatisplus.enums.IEnum; // 导入 IEnum 接口
/** /**
* * IEnum
*/ */
public enum BizTypeEnum implements IEnum { public enum BizTypeEnum implements IEnum {
DOCUMENT("document", "文档"); // 文档类型
DOCUMENT("document", "文档");
private String value; private String value; // 枚举值
private String desc; private String desc; // 枚举描述
/**
*
* @param value
* @param desc
*/
BizTypeEnum(final String value, final String desc) { BizTypeEnum(final String value, final String desc) {
this.value = value; this.value = value;
this.desc = desc; this.desc = desc;
} }
/**
*
* @return
*/
public Serializable getValue() { public Serializable getValue() {
return this.value; return this.value;
} }
/**
*
* @return
*/
public String getDesc(){ public String getDesc(){
return this.desc; return this.desc;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return this.value; return this.value;
} }
} }

@ -4,30 +4,53 @@ import java.io.Serializable;
import com.baomidou.mybatisplus.enums.IEnum; import com.baomidou.mybatisplus.enums.IEnum;
/** /**
* *
*/ */
public enum DocumentStatusEnum implements IEnum { public enum DocumentStatusEnum implements IEnum {
NORMAL("normal", "正常"), /**
HISTORY("history", "历史版本"); *
*/
NORMAL("normal", "正常"),
/**
*
*/
HISTORY("history", "历史版本");
private String value; private String value; // 状态值
private String desc; private String desc; // 状态描述
/**
*
* @param value
* @param desc
*/
DocumentStatusEnum(final String value, final String desc) { DocumentStatusEnum(final String value, final String desc) {
this.value = value; this.value = value;
this.desc = desc; this.desc = desc;
} }
/**
*
* @return
*/
public Serializable getValue() { public Serializable getValue() {
return this.value; return this.value;
} }
/**
*
* @return
*/
public String getDesc(){ public String getDesc(){
return this.desc; return this.desc;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return this.value; return this.value;
} }
} }

@ -4,30 +4,53 @@ import java.io.Serializable;
import com.baomidou.mybatisplus.enums.IEnum; import com.baomidou.mybatisplus.enums.IEnum;
/** /**
* *
*/ */
public enum FileUploadStatusEnum implements IEnum { public enum FileUploadStatusEnum implements IEnum {
NORMAL("normal", "正常"), /**
DELETE("delete", "删除"); *
*/
NORMAL("normal", "正常"),
/**
*
*/
DELETE("delete", "删除");
private String value; private String value; // 状态值
private String desc; private String desc; // 状态描述
/**
*
* @param value
* @param desc
*/
FileUploadStatusEnum(final String value, final String desc) { FileUploadStatusEnum(final String value, final String desc) {
this.value = value; this.value = value;
this.desc = desc; this.desc = desc;
} }
/**
*
* @return
*/
public Serializable getValue() { public Serializable getValue() {
return this.value; return this.value;
} }
/**
*
* @return
*/
public String getDesc(){ public String getDesc(){
return this.desc; return this.desc;
} }
/**
* toString
* @return
*/
@Override @Override
public String toString() { public String toString() {
return this.value; return this.value;
} }
} }

@ -11,22 +11,30 @@ import com.tamguo.modules.book.dao.BookMapper;
import com.tamguo.modules.book.model.BookEntity; import com.tamguo.modules.book.model.BookEntity;
import com.tamguo.modules.book.service.IBookService; import com.tamguo.modules.book.service.IBookService;
/**
* BookServiceImpl IBookService
*/
@Service(value="bbookServiceImpl") @Service(value="bbookServiceImpl")
public class BookServiceImpl extends ServiceImpl<BookMapper, BookEntity> implements IBookService{ public class BookServiceImpl extends ServiceImpl<BookMapper, BookEntity> implements IBookService {
/**
*
*
* @param book
*/
@Transactional(readOnly=false) @Transactional(readOnly=false)
@Override @Override
public void saveBook(BookEntity book) { public void saveBook(BookEntity book) {
book.setCreateDate(new Date()); book.setCreateDate(new Date()); // 设置创建日期为当前日期
book.setUpdateDate(new Date()); book.setUpdateDate(new Date()); // 设置更新日期为当前日期
book.setSeoDescription(book.getName()); book.setSeoDescription(book.getName()); // 设置 SEO 描述为书籍名称
book.setSeoKeywords(book.getName()); book.setSeoKeywords(book.getName()); // 设置 SEO 关键词为书籍名称
book.setSeoTitle(book.getName()); book.setSeoTitle(book.getName()); // 设置 SEO 标题为书籍名称
if(StringUtils.isEmpty(book.getId())) {
this.insert(book); if (StringUtils.isEmpty(book.getId())) { // 如果书籍 ID 为空
}else { this.insert(book); // 执行插入操作
this.updateById(book); } else {
this.updateById(book); // 执行更新操作
} }
} }
}
}

@ -12,14 +12,23 @@ import com.tamguo.modules.book.model.DocumentEntity;
import com.tamguo.modules.book.model.enums.DocumentStatusEnum; import com.tamguo.modules.book.model.enums.DocumentStatusEnum;
import com.tamguo.modules.book.service.IDocumentService; import com.tamguo.modules.book.service.IDocumentService;
/**
* DocumentServiceImpl IDocumentService
*/
@Service @Service
public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, DocumentEntity> implements IDocumentService{ public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, DocumentEntity> implements IDocumentService {
@Transactional(readOnly=false) /**
*
*
* @param document
*/
@Transactional(readOnly = false)
@Override @Override
public void modify(DocumentEntity document) { public void modify(DocumentEntity document) {
DocumentEntity entity = this.selectById(document.getId()); DocumentEntity entity = this.selectById(document.getId()); // 根据 ID 获取文档实体
if("yes".equals(document.getCover())) {
if ("yes".equals(document.getCover())) {
// 覆盖修改 // 覆盖修改
entity.setContent(document.getContent()); entity.setContent(document.getContent());
entity.setMarkdown(document.getMarkdown()); entity.setMarkdown(document.getMarkdown());
@ -28,47 +37,51 @@ public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, DocumentEnt
} else { } else {
String content = entity.getContent(); String content = entity.getContent();
String markdown = entity.getMarkdown(); String markdown = entity.getMarkdown();
// 更新内容 // 更新内容
entity.setContent(document.getContent()); entity.setContent(document.getContent());
entity.setMarkdown(document.getMarkdown()); entity.setMarkdown(document.getMarkdown());
this.updateById(entity); this.updateById(entity);
// 新增历史 // 新增历史
document.setId(null); Document.setId(null);
document.setContent(content); Document.setContent(content);
document.setMarkdown(markdown); Document.setMarkdown(markdown);
document.setBookId(entity.getBookId()); Document.setBookId(entity.getBookId());
document.setCreateDate(new Date()); Document.setCreateDate(new Date());
document.setIsOpen(entity.getIsOpen()); Document.setIsOpen(entity.getIsOpen());
document.setName(entity.getName()); Document.setName(entity.getName());
document.setOwner(entity.getOwner()); Document.setOwner(entity.getOwner());
document.setParentId(entity.getParentId()); Document.setParentId(entity.getParentId());
document.setUpdateDate(new Date()); Document.setUpdateDate(new Date());
document.setStatus(DocumentStatusEnum.HISTORY); Document.setStatus(DocumentStatusEnum.HISTORY);
document.setBatchNo(entity.getBatchNo()); Document.setBatchNo(entity.getBatchNo());
this.insert(document); this.insert(document);
} }
} }
/**
*
*
* @param document
*/
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
@Transactional(readOnly=false) @Transactional(readOnly = false)
@Override @Override
public void create(DocumentEntity document) { public void create(DocumentEntity document) {
if(StringUtils.isEmpty(document.getId())) { if (StringUtils.isEmpty(document.getId())) {
// 如果文档 ID 为空
document.setStatus(DocumentStatusEnum.NORMAL); document.setStatus(DocumentStatusEnum.NORMAL);
document.setCreateDate(new Date()); document.setCreateDate(new Date());
document.setUpdateDate(new Date()); document.setUpdateDate(new Date());
document.setOwner("system"); document.setOwner("system");
document.setBatchNo(new com.baomidou.mybatisplus.toolkit.IdWorker().getIdStr()); document.setBatchNo(new com.baomidou.mybatisplus.toolkit.IdWorker().getIdStr());
this.insert(document); this.insert(document);
}else { } else {
DocumentEntity entity = this.selectById(document.getId()); DocumentEntity entity = this.selectById(document.getId());
entity.setName(document.getName()); entity.setName(document.getName());
entity.setIsOpen(document.getIsOpen()); entity.setIsOpen(document.getIsOpen());
this.updateById(entity); this.updateById(entity);
} }
} }
}
}

@ -9,27 +9,44 @@ import com.baomidou.mybatisplus.annotations.TableName;
import com.tamguo.config.dao.SuperEntity; import com.tamguo.config.dao.SuperEntity;
import lombok.Data; import lombok.Data;
/**
* MemberEntity
*/
@Data @Data
@TableName(value="t_member") @TableName(value="t_member")
public class MemberEntity extends SuperEntity<MemberEntity> implements Serializable { public class MemberEntity extends SuperEntity<MemberEntity> implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 用户名
private String username; private String username;
// 昵称
private String nickName; private String nickName;
// 密码
private String password; private String password;
// 头像
private String avatar; private String avatar;
// 手机号
private String mobile; private String mobile;
// 邮箱
private String email; private String email;
// 积分
private Integer point; private Integer point;
// 余额
private BigDecimal amount; private BigDecimal amount;
// 最后登录时间
private Date lastLoginTime; private Date lastLoginTime;
// 发布文章数
private Integer paperNum; private Integer paperNum;
// 提问数
private Integer questionNum; private Integer questionNum;
// 下载数
private Integer downNum; private Integer downNum;
// 点击数
private Integer hitsNum; private Integer hitsNum;
// 验证码(数据库中不存在该字段)
@TableField(exist=false) @TableField(exist=false)
private String verifyCode; private String verifyCode;
// 当前密码(数据库中不存在该字段)
@TableField(exist=false) @TableField(exist=false)
private String nowPassword; private String nowPassword;
} }

@ -1,43 +1,99 @@
package com.tamguo.modules.member.model.condition; package com.tamguo.modules.member.model.condition;
/**
* MemberCondition
*/
public class MemberCondition { public class MemberCondition {
// 当前页码
private Integer pageNo; private Integer pageNo;
// 每页显示数量
private Integer pageSize; private Integer pageSize;
// 手机号码
private String mobile; private String mobile;
// 用户名
private String username; private String username;
// 昵称
private String nickName; private String nickName;
/**
*
* @return
*/
public String getMobile() { public String getMobile() {
return mobile; return mobile;
} }
/**
*
* @param mobile
*/
public void setMobile(String mobile) { public void setMobile(String mobile) {
this.mobile = mobile; this.mobile = mobile;
} }
/**
*
* @return
*/
public String getUsername() { public String getUsername() {
return username; return username;
} }
/**
*
* @param username
*/
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
/**
*
* @return
*/
public String getNickName() { public String getNickName() {
return nickName; return nickName;
} }
/**
*
* @param nickName
*/
public void setNickName(String nickName) { public void setNickName(String nickName) {
this.nickName = nickName; this.nickName = nickName;
} }
/**
*
* @return
*/
public Integer getPageNo() { public Integer getPageNo() {
return pageNo; return pageNo;
} }
/**
*
* @param pageNo
*/
public void setPageNo(Integer pageNo) { public void setPageNo(Integer pageNo) {
this.pageNo = pageNo; this.pageNo = pageNo;
} }
/**
*
* @return
*/
public Integer getPageSize() { public Integer getPageSize() {
return pageSize; return pageSize;
} }
/**
*
* @param pageSize
*/
public void setPageSize(Integer pageSize) { public void setPageSize(Integer pageSize) {
this.pageSize = pageSize; this.pageSize = pageSize;
} }
}
}

@ -239,49 +239,532 @@ public class MemberService extends ServiceImpl<MemberMapper, MemberEntity> imple
if(!entity.getPassword().equals(new Sha256Hash(member.getPassword()).toHex())) { if(!entity.getPassword().equals(new Sha256Hash(member.getPassword()).toHex())) {
return Result.result(501, null, "旧密码错误!"); return Result.result(501, null, "旧密码错误!");
} }
if(!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())){ package com.tamguo.modules.member.service.impl;
return Result.result(502, null, "验证码错误");
}
entity.setPassword(new Sha256Hash(member.getNowPassword()).toHex());
return Result.result(0, null, "修改成功");
}
@SuppressWarnings("unchecked") import java.math.BigDecimal;
@Transactional(readOnly=true) import java.util.Date;
@Override import java.util.List;
public Page<MemberEntity> listData(MemberCondition condition) { import java.util.UUID;
Page<MemberEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize()); import org.apache.commons.lang3.StringUtils;
Condition query = Condition.create(); import org.apache.shiro.crypto.hash.Sha256Hash;
if(!StringUtils.isEmpty(condition.getMobile())) { import org.springframework.beans.factory.annotation.Autowired;
query.eq("mobile", condition.getMobile()); import org.springframework.stereotype.Service;
} import org.springframework.transaction.annotation.Transactional;
if(!StringUtils.isEmpty(condition.getNickName())) {
query.like("nick_name", condition.getNickName());
}
if(!StringUtils.isEmpty(condition.getUsername())) {
query.eq("username", condition.getUsername());
}
return this.selectPage(page, query);
}
@Transactional(readOnly=false) import com.aliyuncs.exceptions.ClientException;
@Override import com.baomidou.mybatisplus.mapper.Condition;
public void reward(String id ,String bookId , Integer rewardPoint, BigDecimal rewardMoney) { import com.baomidou.mybatisplus.plugins.Page;
MemberEntity member = memberMapper.selectById(id); import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tamguo.common.utils.Result;
// 更新记录 import com.tamguo.common.utils.SystemConstant;
member.setPoint(member.getPoint() + rewardPoint); import com.tamguo.config.redis.CacheService;
member.setAmount(member.getAmount().add(rewardMoney)); import com.tamguo.modules.book.model.BookEntity;
this.updateById(member); import com.tamguo.modules.book.service.IBookService;
import com.tamguo.modules.member.dao.MemberMapper;
BookEntity book = iBookService.selectById(bookId); import com.tamguo.modules.member.model.MemberEntity;
import com.tamguo.modules.member.model.condition.MemberCondition;
// 发送短信 import com.tamguo.modules.member.service.IMemberService;
try { import com.tamguo.modules.sys.service.ISmsService;
iSmsService.sendRewardSms(member.getMobile(), member.getUsername(), book.getName(), rewardPoint, rewardMoney);
} catch (ClientException e) { /**
e.printStackTrace(); * MemberServiceImpl IMemberService
} */
} @Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, MemberEntity> implements IMemberService {
}
// 注入 MemberMapper
@Autowired
private MemberMapper memberMapper;
// 注入 CacheService
@Autowired
private CacheService cacheService;
// 注入 ISmsService
@Autowired
private ISmsService iSmsService;
// 注入 IBookService
@Autowired
private IBookService iBookService;
/**
*
*
* @param username
* @param password
* @return
*/
@Override
public Result login(String username, String password) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户不存在
if (member == null) {
// 返回错误结果,提示用户名 或 password 有误
return Result.result(201, member, "用户名或密码有误,请重新输入或找回密码");
}
// 获取该用户的登录失败次数
Integer loginFailureCount = this.getLoginFailureCount(member);
// 如果密码错误
if (!new Sha256Hash(password).toHex().equals(member.getPassword())) {
// 登录失败次数加 1
loginFailureCount++;
// 更新登录失败次数
this.updateLoginFailureCount(member, loginFailureCount);
// 返回错误结果,提示用户名 或 password 有误
return Result.result(202, member, "用户名或密码有误,请重新输入或找回密码");
}
// 更新登录失败次数为 0
this.updateLoginFailureCount(member, 0);
// 返回正确结果,提示登录成功
return Result.result(200, member, "登录成功");
}
/**
*
*
* @param member
* @param loginFailureCount
*/
public void updateLoginFailureCount(MemberEntity member, Integer loginFailureCount) {
// 将登录失败次数存储到缓存中key 为 LOGIN_FAILURE_COUNT + member.getId()
cacheService.setObject(SystemConstant.LOGIN_FAILURE_COUNT + member.getId(), loginFailureCount, 2 * 60 * 60);
}
/**
*
*
* @param member
* @return
*/
public Integer getLoginFailureCount(MemberEntity member) {
// 如果 member 为空
if (member == null) {
// 返回 0
return 0;
}
// 如果缓存中不存在登录失败次数
if (!cacheService.isExist(SystemConstant.LOGIN_FAILURE_COUNT + member.getId())) {
// 返回 0
return 0;
}
// 从缓存中获取登录失败次数
return (Integer) cacheService.getObject(SystemConstant.LOGIN_FAILURE_COUNT + member.getId());
}
/**
*
*
* @param username
* @return
*/
@Override
public Result checkUsername(String username) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户存在
if (member!= null) {
// 返回错误结果,提示该用户名已经存在
return Result.result(201, null, "该用户名已经存在");
}
// 返回正确结果,提示该用户名可用
return Result.result(200, null, "该用户名可用");
}
/**
*
*
* @param mobile
* @return
*/
@Override
public Result checkMobile(String mobile) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置手机号
condition.setMobile(mobile);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户存在
if (member!= null) {
// 返回错误结果,提示该手机号已经存在
return Result.result(201, null, "该手机号已经存在");
}
// 返回正确结果,提示该手机号可用
return Result.result(200, null, "该手机号可用");
}
/**
*
*
* @param member
* @return
*/
@Transactional(readOnly = false)
@Override
public Result register(MemberEntity member) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(member.getUsername());
// 从数据库中查询该用户
MemberEntity m = memberMapper.selectOne(condition);
// 如果用户已存在
if (m!= null) {
// 返回错误结果,提示该用户已经存在
return Result.result(201, null, "该用户已经存在");
}
// 创建 MemberEntity 对象
condition = new MemberEntity();
// 设置手机号
condition.setMobile(member.getMobile());
// 从数据库中查询该用户
m = memberMapper.selectOne(condition);
// 如果手机号已存在
if (m!= null) {
// 返回错误结果,提示该手机号已经存在
return Result.result(202, null, "该手机号已经存在");
}
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())) {
// 返回错误结果,提示验证码错误
return Result.result(203, null, "验证码错误");
}
// 从缓存中获取验证码
String code = (String) cacheService.getObject(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile());
// 如果验证码错误
if (!code.equals(member.getVerifyCode())) {
// 返回错误结果,提示验证码错误
return Result.result(204, null, "验证码错误");
}
// 创建 MemberEntity 对象
MemberEntity entity = new MemberEntity();
// 设置头像
entity.setAvatar(SystemConstant.DEFAULT_MEMBER_AVATAR);
// 设置手机号
entity.setMobile(member.getMobile());
// 设置密码
entity.setPassword(new Sha256Hash(member.getPassword()).toHex());
// 设置用户名
entity.setUsername(member.getUsername());
// 设置昵称
entity.setNickName(member.getUsername());
// 设置邮箱
entity.setEmail(member.getEmail());
// 插入会员信息
memberMapper.insert(entity);
// 返回正确结果,提示注册成功
return Result.result(200, entity, "注册成功");
}
/**
*
*
* @param account
* @return
*/
@SuppressWarnings("unchecked")
@Override
public Result checkAccount(String account) {
// 如果帐号为空
if (StringUtils.isEmpty(account)) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 创建 Condition 对象
Condition query = Condition.create();
// 添加条件,根据帐号查询会员信息
query.eq("user_name", account).or().eq("mobile", account);
// 从数据库中查询会员信息
List<MemberEntity> members = memberMapper.selectList(query);
// 如果没有查询到会员信息
if (members.size() == 0) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 返回正确结果,提示帐号存在,并返回会员信息
return Result.result(200, members.get(0), "该帐号存在");
}
/**
*
*
* @param account
* @param veritycode
* @return
*/
@SuppressWarnings("unchecked")
@Override
public Result confirmAccount(String account, String veritycode) {
// 如果帐号为空
if (StringUtils.isEmpty(account)) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 创建 Condition 对象
Condition query = Condition.create();
// 添加条件,根据帐号查询会员信息
query.eq("username", account).or().eq("mobile", account);
// 从数据库中查询会员信息
List<MemberEntity> members = memberMapper.selectList(query);
// 如果没有查询到会员信息
if (members.size() == 0) {
// 返回错误结果,提示帐号不存在
return Result.result(201, null, "帐号不存在!");
}
// 返回正确结果,提示帐号存在,并返回会员信息
return Result.result(200, members.get(0), "该帐号存在");
}
/**
*
*
* @param username
* @param isEmail
* @param vcode
* @return
*/
@Override
public Result securityCheck(String username, String isEmail, String vcode) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果用户不存在
if (member == null) {
// 返回错误结果,提示用户不存在
return Result.result(201, member, "用户不存在");
}
// 如果是邮箱验证
if ("1".equals(isEmail)) {
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MAIL_FIND_PASSWORD_PREFIX + member.getEmail())) {
// 返回错误结果,提示验证码错误
return Result.result(201, member, "验证码错误");
}
// 从缓存中获取验证码
String code = (String) cacheService.getObject(SystemConstant.ALIYUN_MAIL_FIND_PASSWORD_PREFIX + member.getEmail());
// 如果验证码错误
if (!code.equals(vcode)) {
// 返回错误结果,提示验证码错误
return Result.result(202, member, "验证码错误");
}
} else {
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())) {
// 返回错误结果,提示验证码错误
return Result.result(203, member, "验证码错误");
}
// 从缓存中获取验证码
String code = (String) cacheService.getObject(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile());
// 如果验证码错误
if (!code.equals(vcode)) {
// 返回错误结果,提示验证码错误
return Result.result(204, member, "验证码错误");
}
}
// 创建随机字符串
String key = UUID.randomUUID().toString();
// 将用户名存储到缓存中key 为 SECURITY_CHECK_PREFIX + key
cacheService.setObject(SystemConstant.SECURITY_CHECK_PREFIX + key, username, 2 * 60 * 60);
// 返回正确结果,提示安全验证通过,并返回随机字符串
return Result.result(200, key, "安全验证通过");
}
/**
*
*
* @param resetPasswordKey key
* @param username
* @param password
* @param verifypwd
* @return
*/
@Override
public Result resetPassword(String resetPasswordKey, String username, String password, String verifypwd) {
// 如果缓存中存在重置密码 key
if (cacheService.isExist(SystemConstant.SECURITY_CHECK_PREFIX + resetPasswordKey)) {
// 创建 MemberEntity 对象
MemberEntity condition = new MemberEntity();
// 设置用户名
condition.setUsername(username);
// 从数据库中查询该用户
MemberEntity member = memberMapper.selectOne(condition);
// 如果密码和确认密码不一致
if (!password.equals(verifypwd)) {
// 返回错误结果,提示密码不一致
return Result.result(201, null, "密码不一致");
}
// 设置密码
member.setPassword(new Sha256Hash(password).toHex());
// 更新会员信息
memberMapper.updateById(member);
}
// 返回正确结果,提示更新成功
return Result.result(200, null, "更新成功");
}
/**
*
*
* @param member
*/
@Transactional(readOnly = false)
@Override
public void updateMember(MemberEntity member) {
// 获取会员信息
MemberEntity entity = memberMapper.selectById(member.getId());
// 设置头像
entity.setAvatar(member.getAvatar());
// 设置邮箱
entity.setEmail(member.getEmail());
// 设置手机号
entity.setMobile(member.getMobile());
// 设置昵称
entity.setNickName(member.getNickName());
// 更新会员信息
memberMapper.updateById(entity);
}
/**
* uid
*
* @param uid uid
* @return
*/
@Transactional(readOnly = true)
@Override
public MemberEntity findByUid(String uid) {
// 根据 uid 查询会员信息
return memberMapper.selectById(uid);
}
/**
*
*
* @param username
* @return
*/
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
@Override
public MemberEntity findByUsername(String username) {
// 创建 Condition 对象
Condition query = Condition.create();
// 添加条件,根据用户名查询会员信息
query.eq("username", username).or().eq("mobile", username).or().eq("email", username);
// 从数据库中查询会员信息
return this.selectOne(query);
}
/**
*
*
* @param uid uid
*/
@Transactional(readOnly = false)
@Override
public void updateLastLoginTime(String uid) {
// 获取会员信息
MemberEntity member = memberMapper.selectById(uid);
// 设置最后登录时间为当前时间
member.setLastLoginTime(new Date());
// 更新会员信息
memberMapper.updateById(member);
}
/**
*
*
* @param id id
* @return
*/
@Override
public MemberEntity findCurrMember(String id) {
// 获取会员信息
MemberEntity member = memberMapper.selectById(id);
// 将密码设置为 null
member.setPassword(null);
// 返回会员信息
return member;
}
/**
*
*
* @param member
* @return
*/
@Transactional(readOnly = false)
@Override
public Result updatePwd(MemberEntity member) {
// 获取会员信息
MemberEntity entity = memberMapper.selectById(member.getId());
// 如果旧密码错误
if (!entity.getPassword().equals(new Sha256Hash(member.getPassword()).toHex())) {
// 返回错误结果,提示旧密码错误
return Result.result(501, null, "旧密码错误!");
}
// 如果缓存中不存在验证码
if (!cacheService.isExist(SystemConstant.ALIYUN_MOBILE_SMS_PREFIX + member.getMobile())){
// 如果缓存服务中不存在指定的验证码前缀与会员手机号的组合
return Result.result(502, null, "验证码错误");
}
entity.setPassword(new Sha256Hash(member.getNowPassword()).toHex());
// 设置实体的密码为会员当前密码的 Sha256 哈希值的十六进制表示
return Result.result(0, null, "修改成功");
}
@SuppressWarnings("unchecked")
@Transactional(readOnly=true)
@Override
public Page<MemberEntity> listData(MemberCondition condition) {
// 创建分页对象
Page<MemberEntity> page = new Page<>(condition.getPageNo(), condition.getPageSize());
Condition query = Condition.create();
// 如果条件中的手机号不为空
if(!StringUtils.isEmpty(condition.getMobile())) {
query.eq("mobile", condition.getMobile());
}
// 如果条件中的昵称不为空
if(!StringUtils.isEmpty(condition.getNickName())) {
query.like("nick_name", condition.getNickName());
}
// 如果条件中的用户名不为空
if(!StringUtils.isEmpty(condition.getUsername())) {
query.eq("username", condition.getUsername());
}
return this.selectPage(page, query);
}
@Transactional(readOnly=false)
@Override
public void reward(String id,String bookId, Integer rewardPoint, BigDecimal rewardMoney) {
MemberEntity member = memberMapper.selectById(id);
// 获取会员实体
// 更新会员的积分和金额
member.setPoint(member.getPoint() + rewardPoint);
member.setAmount(member.getAmount().add(rewardMoney));
this.updateById(member);
BookEntity book = iBookService.selectById(bookId);
// 获取书籍实体
// 发送短信
try {
iSmsService.sendRewardSms(member.getMobile(), member.getUsername(), book.getName(), rewardPoint, rewardMoney);
} catch (ClientException e) {
e.printStackTrace();
}
}

Loading…
Cancel
Save