Skip to main content

ConsistentHashRouter

Struct ConsistentHashRouter 

Source
pub struct ConsistentHashRouter { /* private fields */ }
Expand description

一致性哈希路由器

使用虚拟节点(VNode)让数据分布更均匀。 增减物理节点时,只影响相邻区间的数据,避免全局重分布。

§适用场景

  • 缓存集群(Memcached/Redis 集群)
  • 用户数据分片(保证同一用户始终路由到同一 shard)
  • 需要动态扩缩容的场景

Implementations§

Source§

impl ConsistentHashRouter

Source

pub fn new(nodes: Vec<&str>, vnodes_per_node: usize) -> Self

创建一致性哈希路由器

§参数
  • nodes: 物理节点列表
  • vnodes_per_node: 每个物理节点的虚拟节点数(通常 100-200,越多分布越均匀)
Source

pub fn add_node(&mut self, node: &str)

添加新节点(动态扩容)

Source

pub fn remove_node(&mut self, node: &str)

移除节点(动态缩容)

Source

pub fn route(&self, key: &str) -> Result<String, EnhancedShardingError>

路由 key 到对应节点

§Errors

当 ring 为空时返回 EnhancedShardingError::NoNodes

Source

pub fn nodes(&self) -> &[String]

返回所有物理节点

Source

pub fn ring_size(&self) -> usize

返回环上虚拟节点总数

Source

pub fn vnodes_per_node(&self) -> usize

返回每个物理节点的虚拟节点数

Source

pub fn node_ownership(&self, _node: &str) -> f64

计算某节点负责的 key 比例(0.0-1.0)

通过环上该节点所有虚拟节点的总区间长度 / 2^64 计算。 用于验证分布均匀性。

Trait Implementations§

Source§

impl Debug for ConsistentHashRouter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.