CacheManager¶
High-level facade managing cache operations across backends.
from symphra_cache import CacheManager
from symphra_cache.backends import MemoryBackend
cache = CacheManager(backend=MemoryBackend())
cache.set("k", "v", ttl=60)
assert cache.get("k") == "v"
缓存管理器
提供统一的缓存操作接口,屏蔽底层后端差异。 支持后端动态切换和配置管理。
核心功能: - 统一的同步/异步 API - 后端动态切换 - 批量操作支持 - 类型安全(完整类型注解)
使用示例: >>> from symphra_cache import CacheManager >>> from symphra_cache.backends import MemoryBackend >>> >>> # 创建缓存管理器 >>> cache = CacheManager(backend=MemoryBackend()) >>> >>> # 基础操作 >>> cache.set("user:123", {"name": "Alice"}, ttl=3600) >>> user = cache.get("user:123") >>> >>> # 异步操作 >>> await cache.aset("product:456", {"name": "Laptop"}) >>> product = await cache.aget("product:456") >>> >>> # 批量操作 >>> cache.set_many({"key1": "value1", "key2": "value2"}, ttl=300) >>> results = cache.get_many(["key1", "key2"])
Source code in src/symphra_cache/manager.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 | |
backend
property
¶
获取当前后端实例
Returns:
| Type | Description |
|---|---|
BaseBackend
|
当前使用的后端实例 |
示例
backend = cache.backend print(type(backend).name) # "MemoryBackend"
__init__(backend)
¶
初始化缓存管理器
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
BaseBackend
|
缓存后端实例(Memory/File/Redis) |
required |
示例
backend = MemoryBackend(max_size=10000) cache = CacheManager(backend=backend)
Source code in src/symphra_cache/manager.py
69 70 71 72 73 74 75 76 77 78 79 80 | |
__len__()
¶
获取缓存条目数量
Returns:
| Type | Description |
|---|---|
int
|
缓存中的键数量 |
示例
print(f"缓存中有 {len(cache)} 个条目")
Source code in src/symphra_cache/manager.py
730 731 732 733 734 735 736 737 738 739 740 741 742 | |
acache(ttl=None, key_builder=None, key_prefix='')
¶
异步缓存装饰器(绑定到此管理器实例)
提供更便利的装饰器方式,无需每次都传入 manager 参数。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl
|
int | None
|
缓存过期时间(秒),None 表示永不过期 |
None
|
key_builder
|
KeyBuilder | None
|
自定义键生成函数 |
None
|
key_prefix
|
str
|
键前缀 |
''
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., Any]], Callable[..., Any]]
|
装饰器函数 |
示例: >>> cache = CacheManager(backend=MemoryBackend()) >>> >>> @cache.acache(ttl=600) >>> async def fetch_data(api_url: str): ... async with httpx.AsyncClient() as client: ... response = await client.get(api_url) ... return response.json() >>> >>> data = await fetch_data("https://api.example.com/users")
Source code in src/symphra_cache/manager.py
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 | |
acheck_health()
async
¶
检查后端健康状态(异步)
Returns:
| Type | Description |
|---|---|
bool
|
True 表示健康,False 表示异常 |
示例
is_healthy = await cache.acheck_health()
Source code in src/symphra_cache/manager.py
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | |
aclear()
async
¶
清空所有缓存(异步)
警告
此操作不可逆,会删除所有缓存数据
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
await cache.aclear() # 异步删除所有缓存
Source code in src/symphra_cache/manager.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
aclose()
async
¶
关闭后端连接(异步)
示例
await cache.aclose()
Source code in src/symphra_cache/manager.py
853 854 855 856 857 858 859 860 | |
adecrement(key, delta=1)
async
¶
原子递减计数器(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
delta
|
int
|
减量,默认为 1 |
1
|
Returns:
| Type | Description |
|---|---|
int
|
递减后的值 |
Raises:
| Type | Description |
|---|---|
ValueError
|
当前值不是整数 |
CacheBackendError
|
后端操作失败 |
示例
new_value = await cache.adecrement("counter", 3)
Source code in src/symphra_cache/manager.py
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 | |
adelete(key)
async
¶
删除缓存(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
如果键存在并成功删除返回 True,否则返回 False |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
deleted = await cache.adelete("user:123")
Source code in src/symphra_cache/manager.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
adelete_many(keys)
async
¶
批量删除缓存(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[CacheKey]
|
缓存键列表 |
required |
Returns:
| Type | Description |
|---|---|
int
|
成功删除的键数量 |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
count = await cache.adelete_many(["user:1", "user:2"])
Source code in src/symphra_cache/manager.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | |
aget(key)
async
¶
获取缓存值(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
Returns:
| Type | Description |
|---|---|
CacheValue | None
|
缓存值,不存在或已过期则返回 None |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
user = await cache.aget("user:123")
Source code in src/symphra_cache/manager.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
aget_many(keys)
async
¶
批量获取缓存值(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[CacheKey]
|
缓存键列表 |
required |
Returns:
| Type | Description |
|---|---|
dict[CacheKey, CacheValue]
|
键值对字典,不存在的键不包含在结果中 |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
results = await cache.aget_many(["user:1", "user:2"])
Source code in src/symphra_cache/manager.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
aget_or_set(key, default_factory, ttl=None, ex=False, nx=False)
async
¶
获取缓存值,如果不存在则调用 default_factory 计算并缓存(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
default_factory
|
Callable[[], CacheValue]
|
不存在时调用的工厂函数 |
required |
ttl
|
int | None
|
过期时间(秒),None 表示永不过期 |
None
|
ex
|
bool
|
如果为 True,ttl 表示相对过期时间 |
False
|
nx
|
bool
|
如果为 True,仅当键不存在时才设置 |
False
|
Returns:
| Type | Description |
|---|---|
CacheValue
|
缓存值或计算的新值 |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
async def fetch_data(): ... return await client.get("/api/data") result = await cache.aget_or_set("data", fetch_data)
Source code in src/symphra_cache/manager.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 | |
aincrement(key, delta=1)
async
¶
原子递增计数器(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
delta
|
int
|
增量,默认为 1 |
1
|
Returns:
| Type | Description |
|---|---|
int
|
递增后的值 |
Raises:
| Type | Description |
|---|---|
ValueError
|
当前值不是整数 |
CacheBackendError
|
后端操作失败 |
示例
await cache.aset("counter", 10) new_value = await cache.aincrement("counter", 5)
Source code in src/symphra_cache/manager.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | |
akeys(pattern='*', cursor=0, count=100, max_keys=None)
async
¶
扫描缓存键(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
匹配模式 |
'*'
|
cursor
|
int
|
游标位置 |
0
|
count
|
int
|
每页返回的键数量 |
100
|
max_keys
|
int | None
|
最多返回的键数量 |
None
|
Returns:
| Type | Description |
|---|---|
KeysPage
|
KeysPage 对象 |
示例
page = await cache.akeys(pattern="session:*")
Source code in src/symphra_cache/manager.py
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 | |
amget(keys)
async
¶
批量获取(aget_many 的别名)(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[CacheKey]
|
缓存键列表 |
required |
Returns:
| Type | Description |
|---|---|
dict[CacheKey, CacheValue]
|
键值对字典 |
示例
results = await cache.amget(["key1", "key2"])
Source code in src/symphra_cache/manager.py
679 680 681 682 683 684 685 686 687 688 689 690 691 692 | |
amset(mapping, ttl=None)
async
¶
批量设置(aset_many 的别名)(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict[CacheKey, CacheValue]
|
键值对字典 |
required |
ttl
|
int | None
|
过期时间(秒) |
None
|
示例
await cache.amset({"key1": "val1", "key2": "val2"})
Source code in src/symphra_cache/manager.py
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 | |
aset(key, value, ttl=None, ex=False, nx=False)
async
¶
设置缓存值(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
value
|
CacheValue
|
缓存值 |
required |
ttl
|
int | None
|
过期时间(秒),None 表示永不过期 |
None
|
ex
|
bool
|
如果为 True,ttl 表示相对过期时间 |
False
|
nx
|
bool
|
如果为 True,仅当键不存在时才设置 |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
是否设置成功 |
Raises:
| Type | Description |
|---|---|
CacheSerializationError
|
序列化失败 |
CacheBackendError
|
后端操作失败 |
示例
await cache.aset("product:456", {"name": "Laptop"}, ttl=1800)
Source code in src/symphra_cache/manager.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
aset_many(mapping, ttl=None)
async
¶
批量设置缓存值(异步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict[CacheKey, CacheValue]
|
键值对字典 |
required |
ttl
|
int | None
|
过期时间(秒),None 表示永不过期 |
None
|
Raises:
| Type | Description |
|---|---|
CacheSerializationError
|
序列化失败 |
CacheBackendError
|
后端操作失败 |
示例
await cache.aset_many( ... { ... "product:1": {"name": "Phone"}, ... "product:2": {"name": "Tablet"}, ... } ... )
Source code in src/symphra_cache/manager.py
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | |
cache(ttl=None, key_builder=None, key_prefix='')
¶
缓存装饰器(绑定到此管理器实例)
提供更便利的装饰器方式,无需每次都传入 manager 参数。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl
|
int | None
|
缓存过期时间(秒),None 表示永不过期 |
None
|
key_builder
|
KeyBuilder | None
|
自定义键生成函数 |
None
|
key_prefix
|
str
|
键前缀(用于命名空间隔离) |
''
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., Any]], Callable[..., Any]]
|
装饰器函数 |
示例: >>> cache = CacheManager(backend=MemoryBackend()) >>> >>> @cache.cache(ttl=3600, key_prefix="user:") >>> def get_user(user_id: int): ... return db.query(User).get(user_id) >>> >>> user = get_user(123) # 缓存 1 小时
Source code in src/symphra_cache/manager.py
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 | |
cache_invalidate(key_builder=None, key_prefix='')
¶
缓存失效装饰器(绑定到此管理器实例)
在函数执行后,删除对应的缓存。 常用于更新操作(如 update_user 后清除 get_user 缓存)。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_builder
|
KeyBuilder | None
|
键生成函数(需与 @cache 一致) |
None
|
key_prefix
|
str
|
键前缀 |
''
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[..., Any]], Callable[..., Any]]
|
装饰器函数 |
示例: >>> cache = CacheManager(backend=MemoryBackend()) >>> >>> @cache.cache(key_prefix="user:") >>> def get_user(user_id: int): ... return db.query(User).get(user_id) >>> >>> @cache.cache_invalidate(key_prefix="user:") >>> def update_user(user_id: int, **updates): ... db.query(User).filter_by(id=user_id).update(updates) ... db.commit() >>> >>> get_user(123) # 缓存结果 >>> update_user(123, name="Bob") # 清除缓存 >>> get_user(123) # 重新查询数据库
Source code in src/symphra_cache/manager.py
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 | |
check_health()
¶
检查后端健康状态
Returns:
| Type | Description |
|---|---|
bool
|
True 表示健康,False 表示异常 |
示例
if cache.check_health(): ... print("缓存服务正常")
Source code in src/symphra_cache/manager.py
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |
clear()
¶
清空所有缓存(同步)
警告
此操作不可逆,会删除所有缓存数据
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
cache.clear() # 删除所有缓存
Source code in src/symphra_cache/manager.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
close()
¶
关闭后端连接(同步)
释放所有资源,关闭网络连接等。
示例
cache.close()
Source code in src/symphra_cache/manager.py
842 843 844 845 846 847 848 849 850 851 | |
decrement(key, delta=1)
¶
原子递减计数器(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
delta
|
int
|
减量,默认为 1 |
1
|
Returns:
| Type | Description |
|---|---|
int
|
递减后的值 |
Raises:
| Type | Description |
|---|---|
ValueError
|
当前值不是整数 |
CacheBackendError
|
后端操作失败 |
示例
cache.set("counter", 10) new_value = cache.decrement("counter", 3) print(new_value) # 7
Source code in src/symphra_cache/manager.py
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
delete(key)
¶
删除缓存(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
如果键存在并成功删除返回 True,否则返回 False |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
if cache.delete("user:123"): ... print("缓存已删除")
Source code in src/symphra_cache/manager.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
delete_many(keys)
¶
批量删除缓存(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[CacheKey]
|
缓存键列表 |
required |
Returns:
| Type | Description |
|---|---|
int
|
成功删除的键数量 |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
count = cache.delete_many(["user:1", "user:2", "user:3"]) print(f"删除了 {count} 个键")
Source code in src/symphra_cache/manager.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | |
exists(key)
¶
检查键是否存在(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
如果键存在且未过期返回 True,否则返回 False |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
if cache.exists("user:123"): ... print("缓存存在")
Source code in src/symphra_cache/manager.py
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
from_config(config)
classmethod
¶
从配置创建缓存管理器
支持多种输入类型: - CacheConfig 对象 - dict 配置字典 - str/Path 配置文件路径
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
CacheConfig | dict[str, Any] | str | Path
|
配置对象、字典或文件路径 |
required |
Returns:
| Type | Description |
|---|---|
CacheManager
|
配置好的 CacheManager 实例 |
Raises:
| Type | Description |
|---|---|
CacheConfigError
|
配置验证失败 |
ImportError
|
缺少必需的依赖 |
示例
从字典创建¶
cache = CacheManager.from_config({"backend": "memory"})
从文件创建¶
cache = CacheManager.from_config("config/cache.yaml")
从 CacheConfig 对象创建¶
config = CacheConfig.from_file("cache.toml") cache = CacheManager.from_config(config)
Source code in src/symphra_cache/manager.py
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 | |
from_env(prefix='SYMPHRA_CACHE_')
classmethod
¶
从环境变量创建缓存管理器
环境变量命名规则: - SYMPHRA_CACHE_BACKEND=memory - SYMPHRA_CACHE_MAX_SIZE=10000 - SYMPHRA_CACHE_REDIS_HOST=localhost - SYMPHRA_CACHE_REDIS_PORT=6379
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
环境变量前缀,默认为 "SYMPHRA_CACHE_" |
'SYMPHRA_CACHE_'
|
Returns:
| Type | Description |
|---|---|
CacheManager
|
配置好的 CacheManager 实例 |
Raises:
| Type | Description |
|---|---|
CacheConfigError
|
配置验证失败 |
示例
设置环境变量¶
os.environ["SYMPHRA_CACHE_BACKEND"] = "redis" os.environ["SYMPHRA_CACHE_REDIS_HOST"] = "localhost"
从环境变量创建¶
cache = CacheManager.from_env()
Source code in src/symphra_cache/manager.py
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 | |
from_file(file_path)
classmethod
¶
从配置文件创建缓存管理器
支持的格式: - YAML (.yaml, .yml) - TOML (.toml) - JSON (.json)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
配置文件路径 |
required |
Returns:
| Type | Description |
|---|---|
CacheManager
|
配置好的 CacheManager 实例 |
Raises:
| Type | Description |
|---|---|
CacheConfigError
|
文件读取或解析失败 |
示例
从 YAML 文件创建¶
cache = CacheManager.from_file("config/cache.yaml")
从 TOML 文件创建¶
cache = CacheManager.from_file("config/cache.toml")
Source code in src/symphra_cache/manager.py
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 | |
get(key)
¶
获取缓存值(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
Returns:
| Type | Description |
|---|---|
CacheValue | None
|
缓存值,不存在或已过期则返回 None |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
user = cache.get("user:123") if user is None: ... print("缓存未命中")
Source code in src/symphra_cache/manager.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
get_many(keys)
¶
批量获取缓存值(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[CacheKey]
|
缓存键列表 |
required |
Returns:
| Type | Description |
|---|---|
dict[CacheKey, CacheValue]
|
键值对字典,不存在的键不包含在结果中 |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
results = cache.get_many(["user:1", "user:2", "user:3"]) for key, value in results.items(): ... print(f"{key}: {value}")
Source code in src/symphra_cache/manager.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
get_or_set(key, default_factory, ttl=None, ex=False, nx=False)
¶
获取缓存值,如果不存在则调用 default_factory 计算并缓存
这是防止缓存穿透的推荐模式。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
default_factory
|
Callable[[], CacheValue]
|
不存在时调用的工厂函数 |
required |
ttl
|
int | None
|
过期时间(秒),None 表示永不过期 |
None
|
ex
|
bool
|
如果为 True,ttl 表示相对过期时间 |
False
|
nx
|
bool
|
如果为 True,仅当键不存在时才设置 |
False
|
Returns:
| Type | Description |
|---|---|
CacheValue
|
缓存值或计算的新值 |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
示例
def expensive_compute(): ... return sum(range(1000000)) result = cache.get_or_set("sum", expensive_compute, ttl=300)
Source code in src/symphra_cache/manager.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 | |
increment(key, delta=1)
¶
原子递增计数器(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
delta
|
int
|
增量,默认为 1 |
1
|
Returns:
| Type | Description |
|---|---|
int
|
递增后的值 |
Raises:
| Type | Description |
|---|---|
ValueError
|
当前值不是整数 |
CacheBackendError
|
后端操作失败 |
示例
cache.set("counter", 10) new_value = cache.increment("counter", 5) print(new_value) # 15
Source code in src/symphra_cache/manager.py
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | |
keys(pattern='*', cursor=0, count=100, max_keys=None)
¶
扫描缓存键(同步)
支持模式匹配和分页。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
匹配模式(支持通配符 * 和 ?) |
'*'
|
cursor
|
int
|
游标位置(0 表示开始) |
0
|
count
|
int
|
每页返回的键数量 |
100
|
max_keys
|
int | None
|
最多返回的键数量 |
None
|
Returns:
| Type | Description |
|---|---|
KeysPage
|
KeysPage 对象 |
示例
page = cache.keys(pattern="user:*", count=100) print(f"找到 {len(page.keys)} 个键") if page.has_more: ... next_page = cache.keys(cursor=page.cursor)
Source code in src/symphra_cache/manager.py
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 | |
mget(keys)
¶
批量获取(get_many 的别名)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[CacheKey]
|
缓存键列表 |
required |
Returns:
| Type | Description |
|---|---|
dict[CacheKey, CacheValue]
|
键值对字典 |
示例
results = cache.mget(["key1", "key2", "key3"])
Source code in src/symphra_cache/manager.py
664 665 666 667 668 669 670 671 672 673 674 675 676 677 | |
mset(mapping, ttl=None)
¶
批量设置(set_many 的别名)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict[CacheKey, CacheValue]
|
键值对字典 |
required |
ttl
|
int | None
|
过期时间(秒) |
None
|
示例
cache.mset({"key1": "val1", "key2": "val2"}, ttl=300)
Source code in src/symphra_cache/manager.py
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 | |
set(key, value, ttl=None, ex=False, nx=False)
¶
设置缓存值(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
value
|
CacheValue
|
缓存值 |
required |
ttl
|
int | None
|
过期时间(秒),None 表示永不过期 |
None
|
ex
|
bool
|
如果为 True,ttl 表示相对过期时间;False 表示绝对时间戳 |
False
|
nx
|
bool
|
如果为 True,仅当键不存在时才设置 |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
是否设置成功(nx=True 时可能失败) |
Raises:
| Type | Description |
|---|---|
CacheSerializationError
|
序列化失败 |
CacheBackendError
|
后端操作失败 |
示例
设置 1 小时过期¶
cache.set("session:xyz", {"user_id": 123}, ttl=3600)
仅当不存在时设置(类似 Redis SETNX)¶
success = cache.set("lock:resource", "owner_id", ttl=10, nx=True)
Source code in src/symphra_cache/manager.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
set_many(mapping, ttl=None)
¶
批量设置缓存值(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict[CacheKey, CacheValue]
|
键值对字典 |
required |
ttl
|
int | None
|
过期时间(秒),None 表示永不过期 |
None
|
Raises:
| Type | Description |
|---|---|
CacheSerializationError
|
序列化失败 |
CacheBackendError
|
后端操作失败 |
示例
cache.set_many( ... { ... "user:1": {"name": "Alice"}, ... "user:2": {"name": "Bob"}, ... }, ... ttl=600, ... )
Source code in src/symphra_cache/manager.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | |
switch_backend(backend)
¶
切换缓存后端
注意
切换后端不会迁移现有数据,新后端从空白状态开始
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
BaseBackend
|
新的后端实例 |
required |
示例
从内存后端切换到 Redis 后端¶
from symphra_cache.backends import RedisBackend cache.switch_backend(RedisBackend())
Source code in src/symphra_cache/manager.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 | |
ttl(key)
¶
获取键的剩余生存时间(同步)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
缓存键 |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
剩余秒数,如果键不存在或永不过期返回 None |
Raises:
| Type | Description |
|---|---|
CacheBackendError
|
后端操作失败 |
注意
不同后端的实现精度可能不同
示例
cache.set("temp", "value", ttl=60) remaining = cache.ttl("temp") print(f"剩余 {remaining} 秒")
Source code in src/symphra_cache/manager.py
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 | |