11package tech .smartboot .redisun ;
22
3+ import org .smartboot .socket .transport .WriteBuffer ;
34import tech .smartboot .redisun .resp .RESP ;
45
6+ import java .io .IOException ;
57import java .util .concurrent .CompletableFuture ;
68import java .util .concurrent .ConcurrentLinkedQueue ;
9+ import java .util .concurrent .Semaphore ;
710
811/**
912 * Redis会话管理类
@@ -36,14 +39,14 @@ final class RedisSession {
3639
3740 private int offerCount = 0 ;
3841 private int pollCount = 0 ;
42+ private final WriteBuffer writeBuffer ;
3943
40- public int incrOfferCount ( ) {
41- return ++ offerCount ;
44+ public RedisSession ( WriteBuffer writeBuffer ) {
45+ this . writeBuffer = writeBuffer ;
4246 }
4347
44- public int getOfferCount () {
45- return offerCount ;
46- }
48+ private final ConcurrentLinkedQueue <Tuple > commandQueue = new ConcurrentLinkedQueue <>();
49+ private final Semaphore semaphore = new Semaphore (1 );
4750
4851 /**
4952 * 获取正在解码的响应对象
@@ -68,12 +71,43 @@ public CompletableFuture<RESP> poll() {
6871 return pipeline .poll ();
6972 }
7073
71- public void offer (CompletableFuture <RESP > future ) {
72- pipeline .offer (future );
74+ public void writeCommand (CompletableFuture <RESP > future , Command command ) throws IOException {
75+ if (semaphore .tryAcquire ()) {
76+ offerCount ++;
77+ pipeline .offer (future );
78+ command .writeTo (writeBuffer );
79+ Tuple tuple ;
80+ while ((tuple = commandQueue .poll ()) != null ) {
81+ pipeline .offer (tuple .future );
82+ tuple .command .writeTo (writeBuffer );
83+ }
84+ writeBuffer .flush ();
85+ semaphore .release ();
86+ // flush();
87+ } else {
88+ offerCount ++;
89+ commandQueue .offer (new Tuple (future , command ));
90+ }
7391 }
7492
75- public int getPollCount () {
76- return pollCount ;
93+ public void flush () {
94+ if (commandQueue .isEmpty () || !semaphore .tryAcquire ()) {
95+ return ;
96+ }
97+
98+ try {
99+ Tuple tuple ;
100+ while ((tuple = commandQueue .poll ()) != null ) {
101+ offerCount ++;
102+ pipeline .offer (tuple .future );
103+ tuple .command .writeTo (writeBuffer );
104+ }
105+ } catch (Throwable e ) {
106+ throw new RedisunException (e );
107+ } finally {
108+ semaphore .release ();
109+ }
110+
77111 }
78112
79113 int load () {
@@ -82,4 +116,13 @@ int load() {
82116 return size >= 0 ? size : -size ;
83117 }
84118
119+ private static class Tuple {
120+ private final CompletableFuture <RESP > future ;
121+ private final Command command ;
122+
123+ public Tuple (CompletableFuture <RESP > future , Command command ) {
124+ this .future = future ;
125+ this .command = command ;
126+ }
127+ }
85128}
0 commit comments