6
6
#ifndef COMMON_SESSION_SESSIONMANAGER_H_
7
7
#define COMMON_SESSION_SESSIONMANAGER_H_
8
8
9
+ #include < folly/RWSpinLock.h>
9
10
#include < folly/concurrency/ConcurrentHashMap.h>
10
11
11
12
#include " clients/meta/MetaClient.h"
@@ -23,7 +24,7 @@ namespace nebula {
23
24
24
25
class SessionCount {
25
26
private:
26
- std::atomic<int32_t > count_ = 1 ;
27
+ std::atomic<int32_t > count_{ 0 } ;
27
28
28
29
public:
29
30
int fetch_add (int step) {
@@ -75,11 +76,48 @@ class SessionManager {
75
76
protected:
76
77
using SessionPtr = std::shared_ptr<SessionType>;
77
78
using SessionCountPtr = std::shared_ptr<SessionCount>;
79
+
80
+ // Get session count pointer according to key
81
+ SessionCountPtr sessionCnt (const std::string& key) {
82
+ folly::RWSpinLock::ReadHolder rh (&sessCntLock_);
83
+ auto iter = userIpSessionCount_.find (key);
84
+ if (iter != userIpSessionCount_.end ()) {
85
+ return iter->second ;
86
+ }
87
+ return nullptr ;
88
+ }
89
+
90
+ // add sessionCount
91
+ void addSessionCount (std::string& key) {
92
+ auto sessCntPtr = sessionCnt (key);
93
+ if (!sessCntPtr) {
94
+ folly::RWSpinLock::WriteHolder wh (&sessCntLock_);
95
+ auto iter = userIpSessionCount_.emplace (key, std::make_shared<SessionCount>());
96
+ sessCntPtr = iter.first ->second ;
97
+ }
98
+ sessCntPtr->fetch_add (1 );
99
+ }
100
+
101
+ // sub sessionCount
102
+ void subSessionCount (std::string& key) {
103
+ auto countFindPtr = sessionCnt (key);
104
+ if (countFindPtr) {
105
+ auto count = countFindPtr->fetch_sub (1 );
106
+ if (count == 1 ) {
107
+ folly::RWSpinLock::WriteHolder wh (&sessCntLock_);
108
+ userIpSessionCount_.erase (key);
109
+ }
110
+ }
111
+ }
112
+
78
113
folly::ConcurrentHashMap<SessionID, SessionPtr> activeSessions_;
79
- folly::ConcurrentHashMap<std::string, SessionCountPtr> userIpSessionCount_;
80
114
std::unique_ptr<thread::GenericWorker> scavenger_;
81
115
meta::MetaClient* metaClient_{nullptr };
82
116
HostAddr myAddr_;
117
+
118
+ private:
119
+ folly::RWSpinLock sessCntLock_;
120
+ std::unordered_map<std::string, SessionCountPtr> userIpSessionCount_;
83
121
};
84
122
85
123
} // namespace nebula
0 commit comments