2
2
3
3
import java .util .concurrent .TimeUnit ;
4
4
5
+ import javax .annotation .PostConstruct ;
6
+
5
7
import org .slf4j .Logger ;
6
8
import org .slf4j .LoggerFactory ;
7
9
import org .springframework .beans .factory .annotation .Autowired ;
10
+ import org .springframework .beans .factory .annotation .Value ;
11
+ import org .springframework .boot .actuate .metrics .CounterService ;
8
12
import org .springframework .http .HttpStatus ;
9
13
import org .springframework .stereotype .Service ;
10
14
import org .springframework .transaction .annotation .Transactional ;
@@ -24,12 +28,26 @@ public class AccountService {
24
28
25
29
private static Logger logger = LoggerFactory .getLogger (AccountService .class );
26
30
27
- private Cache <String , Account > loginUsers = CacheBuilder .newBuilder ().maximumSize (1000 )
28
- .expireAfterAccess (10 , TimeUnit .MINUTES ).build ();
29
-
30
31
@ Autowired
31
32
private AccountDao accountDao ;
32
33
34
+ // 注入配置值
35
+ @ Value ("${app.loginTimeoutSecs}" )
36
+ private int loginTimeoutSecs ;
37
+
38
+ // codehale metrics
39
+ @ Autowired
40
+ private CounterService counterService ;
41
+
42
+ // guava cache
43
+ private Cache <String , Account > loginUsers ;
44
+
45
+ @ PostConstruct
46
+ public void init () {
47
+ loginUsers = CacheBuilder .newBuilder ().maximumSize (1000 ).expireAfterAccess (loginTimeoutSecs , TimeUnit .SECONDS )
48
+ .build ();
49
+ }
50
+
33
51
@ Transactional (readOnly = true )
34
52
public String login (String email , String password ) {
35
53
Account account = accountDao .findByEmail (email );
@@ -44,6 +62,7 @@ public String login(String email, String password) {
44
62
45
63
String token = Identities .uuid2 ();
46
64
loginUsers .put (token , account );
65
+ counterService .increment ("loginUser" );
47
66
return token ;
48
67
}
49
68
@@ -53,6 +72,7 @@ public void logout(String token) {
53
72
logger .error ("logout an alreay logout token:" + token );
54
73
} else {
55
74
loginUsers .invalidate (token );
75
+ counterService .decrement ("loginUser" );
56
76
}
57
77
}
58
78
@@ -80,11 +100,7 @@ public void register(String email, String name, String password) {
80
100
accountDao .save (account );
81
101
}
82
102
83
- private static String hashPassword (String password ) {
103
+ protected static String hashPassword (String password ) {
84
104
return Encodes .encodeBase64 (Digests .sha1 (password ));
85
105
}
86
-
87
- public static void main (String [] args ) throws Exception {
88
- System .out .println ("hashPassword:" + hashPassword ("springside" ));
89
- }
90
106
}
0 commit comments