pub trait MemcachedBackend: Send + Sync {
// Required methods
fn get(&self, key: &str) -> Result<Option<Vec<u8>>, CacheError>;
fn set(
&self,
key: &str,
value: Vec<u8>,
ttl: Duration,
) -> Result<(), CacheError>;
fn delete(&self, key: &str) -> Result<bool, CacheError>;
fn increment(&self, key: &str, step: u64) -> Result<i64, CacheError>;
fn decrement(&self, key: &str, step: u64) -> Result<i64, CacheError>;
fn flush(&self) -> Result<(), CacheError>;
fn touch(&self, key: &str, ttl: Duration) -> Result<bool, CacheError>;
}Expand description
Memcached 后端 trait(抽象 Memcached 协议命令)
由于 Rust 端不强制依赖 memcache/memcached crate,本 trait 抽象 Memcached 命令,
允许应用层注入真实 backend。
§命令映射
| Trait 方法 | Memcached 命令 | PHP Memcached 调用 |
|---|---|---|
get | GET | $mc->get($key) |
set | SET(带 TTL) | $mc->set($key, $value, $ttl) |
delete | DELETE | $mc->delete($key) |
increment | INCR | $mc->increment($key, $offset) |
decrement | DECR | $mc->decrement($key, $offset) |
flush | FLUSH_ALL | $mc->flush() |
touch | TOUCH(设置 TTL) | $mc->touch($key, $ttl) |
Required Methods§
Sourcefn set(
&self,
key: &str,
value: Vec<u8>,
ttl: Duration,
) -> Result<(), CacheError>
fn set( &self, key: &str, value: Vec<u8>, ttl: Duration, ) -> Result<(), CacheError>
SET 命令 — 写入缓存(带 TTL)
Memcached 的 SET 必须指定 TTL,若 TTL 为 0 或超过 30 天, Memcached 会将其视为 Unix 时间戳。
Sourcefn delete(&self, key: &str) -> Result<bool, CacheError>
fn delete(&self, key: &str) -> Result<bool, CacheError>
DELETE 命令 — 删除缓存
返回是否删除成功(key 存在且删除成功返回 true)
Sourcefn increment(&self, key: &str, step: u64) -> Result<i64, CacheError>
fn increment(&self, key: &str, step: u64) -> Result<i64, CacheError>
INCR 命令 — 自增
key 不存在时 Memcached 返回错误(与 Redis 不同)。 本 trait 约定:key 不存在时初始化为 0 再 INCR。
Sourcefn decrement(&self, key: &str, step: u64) -> Result<i64, CacheError>
fn decrement(&self, key: &str, step: u64) -> Result<i64, CacheError>
DECR 命令 — 自减
Memcached 的 DECR 不会变为负数(最小为 0)。
Sourcefn flush(&self) -> Result<(), CacheError>
fn flush(&self) -> Result<(), CacheError>
FLUSH_ALL 命令 — 清空所有缓存
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".