1use std::error::Error;
2use std::sync::mpsc::{Sender};
3use crate::redis::Redis;
4use json::{JsonValue};
5use std::sync::RwLock;
6use once_cell::sync::Lazy;
7pub use crate::config::{CacheMode, Config, Connection};
8use crate::redis_pool::{init_redis_pool};
9
10pub mod config;
11mod redis;
12pub mod redis_pool;
13
14static GLOBAL_CONFIG: Lazy<RwLock<Config>> = Lazy::new(|| {
15 RwLock::new(Config::default())
16});
17
18#[derive(Clone)]
19pub enum Cache {
20 Redis(Redis),
21 None,
22}
23
24impl Cache {
25 pub fn new(config: Config) -> Self {
27 {
28 let mut data = GLOBAL_CONFIG.write().unwrap();
29 data.clone_from(&config);
30 }
31 let config = GLOBAL_CONFIG.read().unwrap();
32 let connection = config.connections.get(config.default.as_str()).unwrap().clone();
33 match connection.mode {
34 CacheMode::Redis => {
35 match Redis::connect(connection) {
36 Ok(e) => Cache::Redis(e),
37 Err(_) => Cache::None
38 }
39 }
40 CacheMode::None => Cache::None
41 }
42 }
43
44
45 pub fn new_pool(config: Config, max_size: u32, min_idle: u32) -> bool {
47 {
48 let mut data = GLOBAL_CONFIG.write().unwrap();
49 data.clone_from(&config);
50 }
51 let config = GLOBAL_CONFIG.read().unwrap();
52 let connection = config.connections.get(config.default.as_str()).unwrap().clone();
53 match connection.mode {
54 CacheMode::Redis => {
55 init_redis_pool(connection, max_size, min_idle).unwrap_or_else(|_| false)
56 }
57 CacheMode::None => false
58 }
59 }
60
61
62 pub fn create(name: &str, connection: Connection) -> Self {
64 {
65 let mut data = GLOBAL_CONFIG.write().unwrap();
66 if !data.connections.contains_key(name) {
67 data.connections.insert(name.to_string(), connection);
68 }
69 data.default = name.to_string();
70 }
71 let config = GLOBAL_CONFIG.read().unwrap();
72 let connection = config.connections.get(config.default.as_str()).unwrap().clone();
73 match connection.mode {
74 CacheMode::Redis => {
75 match Redis::connect(connection) {
76 Ok(e) => Cache::Redis(e),
77 Err(_) => Cache::None
78 }
79 }
80 CacheMode::None => Cache::None
81 }
82 }
83 pub fn connections(&mut self) -> JsonValue {
85 let mut connections = vec![];
86 let data = GLOBAL_CONFIG.read().unwrap();
87 for (item, mut value) in data.connections.clone() {
88 if value.mode.str().is_empty() {
89 continue;
90 }
91 let mut t = value.json();
92 t["name"] = item.into();
93 connections.push(t);
94 }
95 connections.into()
96 }
97 pub fn connection(&mut self, name: &str) -> Self {
99 let mut data = GLOBAL_CONFIG.write().unwrap();
100 if data.connections.contains_key(name) {
101 if name == data.default {
102 return self.clone();
103 }
104 data.default = name.to_string();
105 let connection = data.connections.get(data.default.as_str()).unwrap().clone();
106 match connection.mode {
107 CacheMode::Redis => {
108 match Redis::connect(connection) {
109 Ok(e) => Cache::Redis(e),
110 Err(_) => Cache::None
111 }
112 }
113 CacheMode::None => Cache::None
114 }
115 } else {
116 Cache::None
117 }
118 }
119}
120
121
122pub trait CacheBase {
123 fn db(&mut self, db: i8) -> &mut Self;
125
126 fn key_exists(&mut self, key: &str) -> Result<bool, String>;
128 fn key_del(&mut self, key: &str) -> Result<bool, String>;
130 fn key_ttl(&mut self, key: &str) -> Result<i64, String>;
132
133 fn key_set_expireat(&mut self, key: &str, timestamp: i64) -> Result<bool, String>;
137 fn key_set_seconds(&mut self, key: &str, s: i64) -> Result<bool, String>;
140 fn key_del_expire(&mut self, key: &str) -> Result<bool, String>;
142 fn key_query(&mut self, key: &str) -> Result<JsonValue, String>;
145
146 fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String>;
150 fn get(&mut self, key: &str) -> Result<JsonValue, String>;
152
153 fn set_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
155 fn set_count(&mut self, key: &str) -> Result<usize, String>;
157 fn set_get(&mut self, key: &str) -> Result<JsonValue, String>;
159 fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
161 fn set_get_sinter(&mut self, keys: Vec<&str>) -> Result<JsonValue, String>;
163 fn set_get_sunion(&mut self, keys: Vec<&str>) -> Result<JsonValue, String>;
165
166 fn list_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
168 fn list_del(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
170 fn list_lpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
172 fn list_rpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String>;
174 fn list_lpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String>;
177 fn list_rpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String>;
179 fn list_len(&mut self, key: &str) -> Result<usize, String>;
181 fn list_range(&mut self, key: &str, start: isize, stop: isize) -> Result<Vec<JsonValue>, String>;
183 fn list_all(&mut self, key: &str) -> Result<Vec<JsonValue>, String>;
185 fn list_get(&mut self, key: &str, index: isize) -> Result<JsonValue, String>;
187 fn list_trim(&mut self, key: &str, start: isize, stop: isize) -> Result<bool, String>;
189 fn list_set(&mut self, key: &str, index: isize, value: JsonValue) -> Result<bool, String>;
191 fn list_remove(&mut self, key: &str, value: JsonValue, count: isize) -> Result<isize, String>;
193 fn hash_get(&mut self, key: &str) -> Result<JsonValue, String>;
195 fn hash_add(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
197 fn hash_get_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String>;
199 fn hash_get_fields(&mut self, key: &str) -> Result<JsonValue, String>;
201 fn hash_delete(&mut self, key: &str, field: &str) -> Result<bool, String>;
203 fn hash_get_values(&mut self, key: &str) -> Result<JsonValue, String>;
205 fn geo_add(&mut self, key: &str, longitude: f64, latitude: f64, value: JsonValue) -> Result<bool, String>;
207 fn geo_get(&mut self, key: &str, value: JsonValue) -> Result<JsonValue, String>;
209 fn geo_dist(&mut self, key: &str, value1: JsonValue, value2: JsonValue) -> Result<JsonValue, String>;
211 fn geo_radius(&mut self, key: &str, value: JsonValue, radius: &str) -> Result<JsonValue, String>;
213
214 fn stream_add(&mut self, key: &str, msg_id: &str, field: &str, value: JsonValue) -> Result<String, String>;
216 fn stream_count(&mut self, key: &str) -> Result<usize, String>;
218 fn stream_get(&mut self, key: &str) -> Result<JsonValue, String>;
220 fn stream_del(&mut self, key: &str, id: &str) -> Result<bool, String>;
222
223 fn stream_group_create(&mut self, key: &str, group: &str) -> Result<bool, String>;
225 fn stream_group_add_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String>;
226 fn stream_group_del_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String>;
227 fn stream_group_del(&mut self, key: &str, group: &str) -> Result<bool, String>;
229 fn stream_group_msg(&mut self, key: &str, group: &str, user: &str) -> Result<JsonValue, String>;
231 fn stream_get_group(&mut self, key: &str, group: &str) -> Result<bool, String>;
233
234 fn stream_get_stream(&mut self, key: &str) -> Result<JsonValue, String>;
235
236 fn subscribe(&mut self, key: &str, tx: Sender<JsonValue>) -> Result<(), String>;
238 fn publish(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
240 fn publish_pool(channel: &str, payload: &str) -> Result<usize, String>;
241}
242
243impl Cache {
244 pub fn db(&mut self, db: i8) -> &mut Self {
245 match self {
246 Cache::Redis(e) => {
247 e.db(db);
248 }
249 Cache::None => {}
250 }
251 self
252 }
253
254 pub fn key_exists(&mut self, key: &str) -> Result<bool, String> {
255 Ok(match self {
256 Cache::Redis(e) => e.key_exists(key)?,
257 Cache::None => return Err("error".to_string()),
258 })
259 }
260
261 pub fn key_del(&mut self, key: &str) -> Result<bool, String> {
262 Ok(match self {
263 Cache::Redis(e) => e.key_del(key)?,
264 Cache::None => return Err("error".to_string()),
265 })
266 }
267
268 pub fn key_ttl(&mut self, key: &str) -> Result<i64, String> {
269 Ok(match self {
270 Cache::Redis(e) => e.key_ttl(key)?,
271 Cache::None => return Err("error".to_string()),
272 })
273 }
274
275
276 pub fn key_set_expireat(&mut self, key: &str, timestamp: i64) -> Result<bool, String> {
277 Ok(match self {
278 Cache::Redis(e) => e.key_set_expireat(key, timestamp)?,
279 Cache::None => return Err("error".to_string()),
280 })
281 }
282
283 pub fn key_set_seconds(&mut self, key: &str, s: i64) -> Result<bool, String> {
284 Ok(match self {
285 Cache::Redis(e) => e.key_set_seconds(key, s)?,
286 Cache::None => return Err("error".to_string()),
287 })
288 }
289
290 pub fn key_del_expire(&mut self, key: &str) -> Result<bool, String> {
291 Ok(match self {
292 Cache::Redis(e) => e.key_del_expire(key)?,
293 Cache::None => return Err("error".to_string()),
294 })
295 }
296
297 pub fn key_query(&mut self, key: &str) -> Result<JsonValue, String> {
298 let res = match self {
299 Cache::Redis(e) => e.key_query(key)?,
300 Cache::None => return Err("error".to_string()),
301 };
302 Ok(res)
303 }
304 pub fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String> {
305 Ok(match self {
306 Cache::Redis(e) => e.add(key, value, expiration_date)?,
307 Cache::None => return Err("error".to_string()),
308 })
309 }
310 pub fn get(&mut self, key: &str) -> Result<JsonValue, String> {
311 let res = match self {
312 Cache::Redis(e) => e.get(key)?,
313 Cache::None => return Err("error".to_string()),
314 };
315 Ok(res)
316 }
317
318
319 pub fn set_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
320 let res = match self {
321 Cache::Redis(e) => e.set_add(key, value, expiry_s)?,
322 Cache::None => return Err("error".to_string()),
323 };
324 Ok(res)
325 }
326 pub fn set_count(&mut self, key: &str) -> Result<usize, String> {
327 let res = match self {
328 Cache::Redis(e) => e.set_count(key)?,
329 Cache::None => return Err("error".to_string()),
330 };
331 Ok(res)
332 }
333 pub fn set_get(&mut self, key: &str) -> Result<JsonValue, String> {
334 let res = match self {
335 Cache::Redis(e) => e.set_get(key)?,
336 Cache::None => return Err("error".to_string()),
337 };
338 Ok(res)
339 }
340
341 pub fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
342 Ok(match self {
343 Cache::Redis(e) => e.set_delete(key, value)?,
344 Cache::None => return Err("error".to_string()),
345 })
346 }
347
348 pub fn set_get_sinter(&mut self, keys: Vec<&str>) -> Result<JsonValue, String> {
349 Ok(match self {
350 Cache::Redis(e) => e.set_get_sinter(keys)?,
351 Cache::None => return Err("error".to_string()),
352 })
353 }
354
355 pub fn set_get_sunion(&mut self, keys: Vec<&str>) -> Result<JsonValue, String> {
356 Ok(match self {
357 Cache::Redis(e) => e.set_get_sunion(keys)?,
358 Cache::None => return Err("error".to_string()),
359 })
360 }
361
362 pub fn list_add(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
363 Ok(match self {
364 Cache::Redis(e) => e.list_add(key, value, expiry_s)?,
365 Cache::None => return Err("error".to_string()),
366 })
367 }
368
369 pub fn list_del(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
370 Ok(match self {
371 Cache::Redis(e) => e.list_del(key, value)?,
372 Cache::None => return Err("error".to_string()),
373 })
374 }
375
376 pub fn list_lpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
378 Ok(match self {
379 Cache::Redis(e) => e.list_lpush(key, value, expiry_s)?,
380 Cache::None => return Err("Redis连接未初始化".to_string()),
381 })
382 }
383
384 pub fn list_rpush(&mut self, key: &str, value: JsonValue, expiry_s: i64) -> Result<bool, String> {
386 Ok(match self {
387 Cache::Redis(e) => e.list_rpush(key, value, expiry_s)?,
388 Cache::None => return Err("Redis连接未初始化".to_string()),
389 })
390 }
391
392 pub fn list_lpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String> {
394 Ok(match self {
395 Cache::Redis(e) => e.list_lpop(key, count)?,
396 Cache::None => return Err("Redis连接未初始化".to_string()),
397 })
398 }
399
400 pub fn list_rpop(&mut self, key: &str, count: usize) -> Result<Vec<JsonValue>, String> {
402 Ok(match self {
403 Cache::Redis(e) => e.list_rpop(key, count)?,
404 Cache::None => return Err("Redis连接未初始化".to_string()),
405 })
406 }
407
408 pub fn list_len(&mut self, key: &str) -> Result<usize, String> {
410 Ok(match self {
411 Cache::Redis(e) => e.list_len(key)?,
412 Cache::None => return Err("Redis连接未初始化".to_string()),
413 })
414 }
415
416 pub fn list_range(&mut self, key: &str, start: isize, stop: isize) -> Result<Vec<JsonValue>, String> {
418 Ok(match self {
419 Cache::Redis(e) => e.list_range(key, start, stop)?,
420 Cache::None => return Err("Redis连接未初始化".to_string()),
421 })
422 }
423
424 pub fn list_all(&mut self, key: &str) -> Result<Vec<JsonValue>, String> {
426 Ok(match self {
427 Cache::Redis(e) => e.list_all(key)?,
428 Cache::None => return Err("Redis连接未初始化".to_string()),
429 })
430 }
431
432 pub fn list_get(&mut self, key: &str, index: isize) -> Result<JsonValue, String> {
434 Ok(match self {
435 Cache::Redis(e) => e.list_get(key, index)?,
436 Cache::None => return Err("Redis连接未初始化".to_string()),
437 })
438 }
439
440 pub fn list_trim(&mut self, key: &str, start: isize, stop: isize) -> Result<bool, String> {
442 Ok(match self {
443 Cache::Redis(e) => e.list_trim(key, start, stop)?,
444 Cache::None => return Err("Redis连接未初始化".to_string()),
445 })
446 }
447
448 pub fn list_set(&mut self, key: &str, index: isize, value: JsonValue) -> Result<bool, String> {
450 Ok(match self {
451 Cache::Redis(e) => e.list_set(key, index, value)?,
452 Cache::None => return Err("Redis连接未初始化".to_string()),
453 })
454 }
455
456 pub fn list_remove(&mut self, key: &str, value: JsonValue, count: isize) -> Result<isize, String> {
458 Ok(match self {
459 Cache::Redis(e) => e.list_remove(key, value, count)?,
460 Cache::None => return Err("Redis连接未初始化".to_string()),
461 })
462 }
463
464
465 pub fn hash_get(&mut self, key: &str) -> Result<JsonValue, String> {
467 let res = match self {
468 Cache::Redis(e) => e.hash_get(key)?,
469 Cache::None => return Err("error".to_string()),
470 };
471 Ok(res)
472 }
473 pub fn hash_add(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
475 Ok(match self {
476 Cache::Redis(e) => e.hash_add(key, field, value)?,
477 Cache::None => return Err("error".to_string()),
478 })
479 }
480 pub fn hash_get_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String> {
482 let res = match self {
483 Cache::Redis(e) => e.hash_get_field_value(key, field)?,
484 Cache::None => return Err("error".to_string()),
485 };
486 Ok(res)
487 }
488 pub fn hash_get_fields(&mut self, key: &str) -> Result<JsonValue, String> {
490 Ok(match self {
491 Cache::Redis(e) => e.hash_get_fields(key)?,
492 Cache::None => return Err("error".to_string()),
493 })
494 }
495 pub fn hash_delete(&mut self, key: &str, field: &str) -> Result<bool, String> {
496 Ok(match self {
497 Cache::Redis(e) => e.hash_delete(key, field)?,
498 Cache::None => return Err("error".to_string()),
499 })
500 }
501 pub fn hash_get_values(&mut self, key: &str) -> Result<JsonValue, String> {
503 Ok(match self {
504 Cache::Redis(e) => e.hash_get_values(key)?,
505 Cache::None => return Err("error".to_string()),
506 })
507 }
508
509 pub fn geo_add(&mut self, key: &str, longitude: f64, latitude: f64, value: JsonValue) -> Result<bool, String> {
510 Ok(match self {
511 Cache::Redis(e) => e.geo_add(key, longitude, latitude, value)?,
512 Cache::None => return Err("error".to_string()),
513 })
514 }
515
516
517 pub fn geo_get(&mut self, key: &str, value: JsonValue) -> Result<JsonValue, String> {
518 Ok(match self {
519 Cache::Redis(e) => e.geo_get(key, value)?,
520 Cache::None => return Err("error".to_string()),
521 })
522 }
523
524 pub fn geo_dist(&mut self, key: &str, value1: JsonValue, value2: JsonValue) -> Result<JsonValue, String> {
525 Ok(match self {
526 Cache::Redis(e) => e.geo_dist(key, value1, value2)?,
527 Cache::None => return Err("error".to_string()),
528 })
529 }
530
531 pub fn geo_radius(&mut self, key: &str, value: JsonValue, radius: &str) -> Result<JsonValue, String> {
532 Ok(match self {
533 Cache::Redis(e) => e.geo_radius(key, value, radius)?,
534 Cache::None => return Err("error".to_string()),
535 })
536 }
537 pub fn stream_add(&mut self, key: &str, msg_id: &str, field: &str, value: JsonValue) -> Result<String, String> {
538 match self {
539 Cache::Redis(e) => e.stream_add(key, msg_id, field, value),
540 Cache::None => Err("error".to_string()),
541 }
542 }
543 pub fn stream_count(&mut self, key: &str) -> Result<usize, String> {
544 Ok(match self {
545 Cache::Redis(e) => e.stream_count(key)?,
546 Cache::None => return Err("error".to_string()),
547 })
548 }
549
550 pub fn stream_get(&mut self, key: &str) -> Result<JsonValue, String> {
551 Ok(match self {
552 Cache::Redis(e) => e.stream_get(key)?,
553 Cache::None => return Err("error".to_string()),
554 })
555 }
556
557
558 pub fn stream_del(&mut self, key: &str, id: &str) -> Result<bool, String> {
559 Ok(match self {
560 Cache::Redis(e) => e.stream_del(key, id)?,
561 Cache::None => return Err("error".to_string()),
562 })
563 }
564
565 pub fn stream_group_create(&mut self, key: &str, group: &str) -> Result<bool, String> {
566 Ok(match self {
567 Cache::Redis(e) => e.stream_group_create(key, group)?,
568 Cache::None => return Err("error".to_string()),
569 })
570 }
571
572 pub fn stream_group_add_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String> {
573 Ok(match self {
574 Cache::Redis(e) => e.stream_group_add_user(key, group, user)?,
575 Cache::None => return Err("error".to_string()),
576 })
577 }
578
579 pub fn stream_group_del_user(&mut self, key: &str, group: &str, user: &str) -> Result<bool, String> {
580 Ok(match self {
581 Cache::Redis(e) => e.stream_group_del_user(key, group, user)?,
582 Cache::None => return Err("error".to_string()),
583 })
584 }
585
586 pub fn stream_group_del(&mut self, key: &str, group: &str) -> Result<bool, String> {
587 Ok(match self {
588 Cache::Redis(e) => e.stream_group_del(key, group)?,
589 Cache::None => return Err("error".to_string()),
590 })
591 }
592
593 pub fn stream_group_msg(&mut self, key: &str, group: &str, user: &str) -> Result<JsonValue, String> {
594 Ok(match self {
595 Cache::Redis(e) => e.stream_group_msg(key, group, user)?,
596 Cache::None => return Err("error".to_string()),
597 })
598 }
599
600 pub fn stream_get_group(&mut self, key: &str, group: &str) -> Result<bool, String> {
601 Ok(match self {
602 Cache::Redis(e) => e.stream_get_group(key, group)?,
603 Cache::None => return Err("error".to_string()),
604 })
605 }
606
607 pub fn stream_get_stream(&mut self, key: &str) -> Result<JsonValue, String> {
608 Ok(match self {
609 Cache::Redis(e) => e.stream_get_stream(key)?,
610 Cache::None => return Err("error".to_string()),
611 })
612 }
613
614 pub fn subscribe(&mut self, key: &str, tx: Sender<JsonValue>) -> Result<(), String> {
615 let _: () = match self {
616 Cache::Redis(e) => e.subscribe(key, tx)?,
617 Cache::None => return Err("error".to_string()),
618 };
619 Ok(())
620 }
621 pub fn publish(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
622 Ok(match self {
623 Cache::Redis(e) => e.publish(key, value)?,
624 Cache::None => return Err("error".to_string()),
625 })
626 }
627
628 pub fn publish_pool(&mut self, channel: &str, payload: &str) -> Result<usize, String>{
629 Ok(Redis::publish_pool(channel, payload)?)
630 }
631
632}