Skip to content

Commit 4accbe6

Browse files
committed
issue binarywang#69 添加Session的支持
1 parent 7ea6e3e commit 4accbe6

10 files changed

Lines changed: 205 additions & 35 deletions

File tree

‎weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSession.java‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,9 @@ public interface InternalSession {
3939
void access();
4040

4141
/**
42-
* Set the <code>isNew</code> flag for this session.
43-
*
44-
* @param isNew The new value for the <code>isNew</code> flag
42+
* End the access.
4543
*/
46-
void setNew(boolean isNew);
44+
void endAccess();
4745

4846
/**
4947
* Set the creation time for this session. This method is called by the

‎weixin-java-common/src/main/java/me/chanjar/weixin/common/session/SessionImpl.java‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import java.util.*;
66
import java.util.concurrent.ConcurrentHashMap;
7+
import java.util.concurrent.atomic.AtomicInteger;
78

89
public class SessionImpl implements WxSession, InternalSession {
910

@@ -90,11 +91,6 @@ public void invalidate() {
9091
*/
9192
protected volatile boolean isValid = false;
9293

93-
/**
94-
* Flag indicating whether this session is new or not.
95-
*/
96-
protected boolean isNew = false;
97-
9894
/**
9995
* We are currently processing a session expiration, so bypass
10096
* certain IllegalStateException tests. NOTE: This value is not
@@ -123,11 +119,6 @@ public void invalidate() {
123119
*/
124120
protected volatile long thisAccessedTime = creationTime;
125121

126-
/**
127-
* The last accessed time for this Session.
128-
*/
129-
protected volatile long lastAccessedTime = creationTime;
130-
131122
/**
132123
* The default maximum inactive interval for Sessions created by
133124
* this Manager.
@@ -140,9 +131,15 @@ public void invalidate() {
140131
*/
141132
protected transient InternalSessionFacade facade = null;
142133

134+
/**
135+
* The access count for this session.
136+
*/
137+
protected transient AtomicInteger accessCount = null;
138+
143139

144140
public SessionImpl(InternalSessionManager manager) {
145141
this.manager = manager;
142+
this.accessCount = new AtomicInteger();
146143
}
147144

148145

@@ -176,7 +173,28 @@ public void setValid(boolean isValid) {
176173

177174
@Override
178175
public boolean isValid() {
179-
return isValid;
176+
if (!this.isValid) {
177+
return false;
178+
}
179+
180+
if (this.expiring) {
181+
return true;
182+
}
183+
184+
if (accessCount.get() > 0) {
185+
return true;
186+
}
187+
188+
if (maxInactiveInterval > 0) {
189+
long timeNow = System.currentTimeMillis();
190+
int timeIdle;
191+
timeIdle = (int) ((timeNow - thisAccessedTime) / 1000L);
192+
if (timeIdle >= maxInactiveInterval) {
193+
expire();
194+
}
195+
}
196+
197+
return this.isValid;
180198
}
181199

182200
@Override
@@ -215,6 +233,8 @@ public void expire() {
215233
// Mark this session as "being expired"
216234
expiring = true;
217235

236+
accessCount.set(0);
237+
218238
// Remove this session from our manager's active sessions
219239
manager.remove(this, true);
220240

@@ -238,23 +258,23 @@ public void expire() {
238258
public void access() {
239259

240260
this.thisAccessedTime = System.currentTimeMillis();
261+
accessCount.incrementAndGet();
241262

242263
}
243264

244265

245266
@Override
246-
public void setNew(boolean isNew) {
267+
public void endAccess() {
247268

248-
this.isNew = isNew;
269+
this.thisAccessedTime = System.currentTimeMillis();
270+
accessCount.decrementAndGet();
249271

250272
}
251273

252-
253274
@Override
254275
public void setCreationTime(long time) {
255276

256277
this.creationTime = time;
257-
this.lastAccessedTime = time;
258278
this.thisAccessedTime = time;
259279

260280
}

‎weixin-java-common/src/main/java/me/chanjar/weixin/common/session/SessionManagerImpl.java‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import java.util.Map;
88
import java.util.concurrent.ConcurrentHashMap;
9+
import java.util.concurrent.atomic.AtomicBoolean;
910

1011
public class SessionManagerImpl implements WxSessionManager, InternalSessionManager {
1112

@@ -104,6 +105,11 @@ public WxSession getSession(String sessionId, boolean create) {
104105
*/
105106
protected int processExpiresFrequency = 6;
106107

108+
/**
109+
* 后台清理线程是否已经开启
110+
*/
111+
private final AtomicBoolean backgroundProcessStarted = new AtomicBoolean(false);
112+
107113
@Override
108114
public void remove(InternalSession session) {
109115
remove(session, false);
@@ -155,7 +161,6 @@ public InternalSession createSession(String sessionId) {
155161
InternalSession session = createEmptySession();
156162

157163
// Initialize the properties of the new session and return it
158-
session.setNew(true);
159164
session.setValid(true);
160165
session.setCreationTime(System.currentTimeMillis());
161166
session.setMaxInactiveInterval(this.maxInactiveInterval);
@@ -191,6 +196,26 @@ protected InternalSession getNewSession() {
191196
@Override
192197
public void add(InternalSession session) {
193198

199+
// 当第一次有session创建的时候,开启session清理线程
200+
if (!backgroundProcessStarted.getAndSet(true)) {
201+
Thread t = new Thread(new Runnable() {
202+
@Override
203+
public void run() {
204+
while (true) {
205+
try {
206+
// 每秒清理一次
207+
Thread.sleep(1000l);
208+
backgroundProcess();
209+
} catch (InterruptedException e) {
210+
log.error("SessionManagerImpl.backgroundProcess error", e);
211+
}
212+
}
213+
}
214+
});
215+
t.setDaemon(true);
216+
t.start();
217+
}
218+
194219
sessions.put(session.getIdInternal(), session);
195220
int size = getActiveSessions();
196221
if( size > maxActive ) {

‎weixin-java-common/src/main/java/me/chanjar/weixin/common/session/WxSessionManager.java‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,19 @@
22

33
public interface WxSessionManager {
44

5-
5+
/**
6+
* 获取某个sessionId对应的session,如果sessionId没有对应的session,则新建一个并返回。
7+
* @param sessionId
8+
* @return
9+
*/
610
public WxSession getSession(String sessionId);
711

12+
/**
13+
* 获取某个sessionId对应的session,如果sessionId没有对应的session,若create为true则新建一个,否则返回null。
14+
* @param sessionId
15+
* @param create
16+
* @return
17+
*/
818
public WxSession getSession(String sessionId, boolean create);
919

1020

‎weixin-java-common/src/main/java/me/chanjar/weixin/common/util/WxMsgIdMemoryDuplicateChecker.java‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.Map;
44
import java.util.concurrent.ConcurrentHashMap;
5+
import java.util.concurrent.atomic.AtomicBoolean;
56

67
/**
78
* <pre>
@@ -21,8 +22,16 @@ public class WxMsgIdMemoryDuplicateChecker implements WxMsgIdDuplicateChecker {
2122
*/
2223
private final Long clearPeriod;
2324

25+
/**
26+
* 消息id->消息时间戳的map
27+
*/
2428
private final ConcurrentHashMap<Long, Long> msgId2Timestamp = new ConcurrentHashMap<Long, Long>();
2529

30+
/**
31+
* 后台清理线程是否已经开启
32+
*/
33+
private final AtomicBoolean backgroundProcessStarted = new AtomicBoolean(false);
34+
2635
/**
2736
* WxMsgIdInMemoryDuplicateChecker构造函数
2837
* <pre>
@@ -33,7 +42,6 @@ public class WxMsgIdMemoryDuplicateChecker implements WxMsgIdDuplicateChecker {
3342
public WxMsgIdMemoryDuplicateChecker() {
3443
this.timeToLive = 15 * 1000l;
3544
this.clearPeriod = 5 * 1000l;
36-
this.start();
3745
}
3846

3947
/**
@@ -44,10 +52,12 @@ public WxMsgIdMemoryDuplicateChecker() {
4452
public WxMsgIdMemoryDuplicateChecker(Long timeToLive, Long clearPeriod) {
4553
this.timeToLive = timeToLive;
4654
this.clearPeriod = clearPeriod;
47-
this.start();
4855
}
4956

50-
private void start() {
57+
protected void checkBackgroundProcessStarted() {
58+
if (backgroundProcessStarted.getAndSet(true)) {
59+
return;
60+
}
5161
Thread t = new Thread(new Runnable() {
5262
@Override
5363
public void run() {
@@ -72,6 +82,7 @@ public void run() {
7282

7383
@Override
7484
public boolean isDuplicate(Long wxMsgId) {
85+
checkBackgroundProcessStarted();
7586
Long timestamp = msgId2Timestamp.putIfAbsent(wxMsgId, System.currentTimeMillis());
7687
if (timestamp == null) {
7788
// 第一次接收到这个消息

‎weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import me.chanjar.weixin.common.bean.WxMenu;
44
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
55
import me.chanjar.weixin.common.exception.WxErrorException;
6+
import me.chanjar.weixin.common.session.WxSession;
7+
import me.chanjar.weixin.common.session.WxSessionManager;
68
import me.chanjar.weixin.common.util.http.RequestExecutor;
79
import me.chanjar.weixin.cp.bean.WxCpDepart;
810
import me.chanjar.weixin.cp.bean.WxCpMessage;
@@ -371,4 +373,28 @@ public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputS
371373
* @param maxRetryTimes
372374
*/
373375
void setMaxRetryTimes(int maxRetryTimes);
376+
377+
/**
378+
* 获取某个sessionId对应的session,如果sessionId没有对应的session,则新建一个并返回。
379+
* @param id id可以为任意字符串,建议使用FromUserName作为id
380+
* @return
381+
*/
382+
WxSession getSession(String id);
383+
384+
/**
385+
* 获取某个sessionId对应的session,如果sessionId没有对应的session,若create为true则新建一个,否则返回null。
386+
* @param id id可以为任意字符串,建议使用FromUserName作为id
387+
* @param create
388+
* @return
389+
*/
390+
WxSession getSession(String id, boolean create);
391+
392+
/**
393+
* <pre>
394+
* 设置WxSessionManager,只有当需要使用个性化的WxSessionManager的时候才需要调用此方法,
395+
* WxCpService默认使用的是{@link me.chanjar.weixin.common.session.SessionManagerImpl}
396+
* </pre>
397+
* @param sessionManager
398+
*/
399+
void setSessionManager(WxSessionManager sessionManager);
374400
}

‎weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
import me.chanjar.weixin.common.bean.result.WxError;
1313
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
1414
import me.chanjar.weixin.common.exception.WxErrorException;
15+
import me.chanjar.weixin.common.session.SessionManagerImpl;
16+
import me.chanjar.weixin.common.session.WxSession;
17+
import me.chanjar.weixin.common.session.WxSessionManager;
1518
import me.chanjar.weixin.common.util.StringUtils;
1619
import me.chanjar.weixin.common.util.crypto.SHA1;
1720
import me.chanjar.weixin.common.util.fs.FileUtils;
@@ -64,6 +67,8 @@ public class WxCpServiceImpl implements WxCpService {
6467

6568
private int maxRetryTimes = 5;
6669

70+
protected WxSessionManager sessionManager = new SessionManagerImpl();
71+
6772
public boolean checkSignature(String msgSignature, String timestamp, String nonce, String data) {
6873
try {
6974
return SHA1.gen(wxCpConfigStorage.getToken(), timestamp, nonce, data).equals(msgSignature);
@@ -473,4 +478,26 @@ public void setMaxRetryTimes(int maxRetryTimes) {
473478
this.maxRetryTimes = maxRetryTimes;
474479
}
475480

481+
@Override
482+
public WxSession getSession(String id) {
483+
if (sessionManager == null) {
484+
return null;
485+
}
486+
return sessionManager.getSession(id);
487+
}
488+
489+
@Override
490+
public WxSession getSession(String id, boolean create) {
491+
if (sessionManager == null) {
492+
return null;
493+
}
494+
return sessionManager.getSession(id, create);
495+
}
496+
497+
498+
@Override
499+
public void setSessionManager(WxSessionManager sessionManager) {
500+
this.sessionManager = sessionManager;
501+
}
502+
476503
}

0 commit comments

Comments
 (0)