Skip to main content

ConsistentHashRouter

Struct ConsistentHashRouter 

Source
pub struct ConsistentHashRouter<T: Node + Clone> { /* private fields */ }
Expand description

Consistent hash router that maps keys to nodes on a hash ring

This implementation uses virtual nodes to improve key distribution across physical nodes. Each physical node is represented by multiple virtual nodes on the ring.

§Type Parameters

  • T - The type of physical nodes, must implement Node and Clone traits

§Example

use rocketmq_common::common::consistenthash::ConsistentHashRouter;
use rocketmq_common::common::consistenthash::Node;

#[derive(Clone)]
struct ServerNode {
    address: String,
}

impl Node for ServerNode {
    fn get_key(&self) -> &str {
        &self.address
    }
}

let nodes = vec![
    ServerNode {
        address: "192.168.1.1:8080".to_string(),
    },
    ServerNode {
        address: "192.168.1.2:8080".to_string(),
    },
];

let router = ConsistentHashRouter::new(nodes, 10);
let target_node = router.route_node("my-key").unwrap();
println!("Key 'my-key' routes to: {}", target_node.get_key());

Implementations§

Source§

impl<T: Node + Clone> ConsistentHashRouter<T>

Source

pub fn new(physical_nodes: Vec<T>, virtual_node_count: i32) -> Self

Create a new consistent hash router with the default MD5 hash function

§Arguments
  • physical_nodes - Collection of physical nodes to add to the ring
  • virtual_node_count - Number of virtual nodes per physical node
§Returns

A new ConsistentHashRouter instance

§Example
use rocketmq_common::common::consistenthash::ConsistentHashRouter;
use rocketmq_common::common::consistenthash::Node;

#[derive(Clone)]
struct ServerNode {
    name: String,
}

impl Node for ServerNode {
    fn get_key(&self) -> &str {
        &self.name
    }
}

let nodes = vec![
    ServerNode {
        name: "node1".to_string(),
    },
    ServerNode {
        name: "node2".to_string(),
    },
];

let router = ConsistentHashRouter::new(nodes, 150);
Source

pub fn try_new( physical_nodes: Vec<T>, virtual_node_count: i32, ) -> RocketMQResult<Self>

Create a new consistent hash router and return a typed error when the configuration is invalid.

Source

pub fn new_with_hash_function( physical_nodes: Vec<T>, virtual_node_count: i32, hash_function: Arc<dyn HashFunction>, ) -> Self

Create a new consistent hash router with a custom hash function

§Arguments
  • physical_nodes - Collection of physical nodes to add to the ring
  • virtual_node_count - Number of virtual nodes per physical node
  • hash_function - Custom hash function to use
§Returns

A new ConsistentHashRouter instance

§Invalid configuration

This method returns an empty router when virtual_node_count is negative. Use Self::try_new_with_hash_function when invalid configuration must be reported to the caller.

Source

pub fn try_new_with_hash_function( physical_nodes: Vec<T>, virtual_node_count: i32, hash_function: Arc<dyn HashFunction>, ) -> RocketMQResult<Self>

Create a new consistent hash router with a custom hash function and return a typed error when virtual_node_count is negative.

Source

pub fn add_node(&mut self, physical_node: T, virtual_node_count: i32)

Add a physical node to the hash ring with virtual nodes

§Arguments
  • physical_node - Physical node to add to the hash ring
  • virtual_node_count - The number of virtual nodes for this physical node. Value should be greater than or equal to 0
§Invalid configuration

This method is a no-op when virtual_node_count is negative. Use Self::try_add_node when invalid configuration must be reported to the caller.

§Example
use rocketmq_common::common::consistenthash::ConsistentHashRouter;
use rocketmq_common::common::consistenthash::Node;

#[derive(Clone)]
struct ServerNode {
    name: String,
}

impl Node for ServerNode {
    fn get_key(&self) -> &str {
        &self.name
    }
}

let mut router = ConsistentHashRouter::new(vec![], 0);
let node = ServerNode {
    name: "node1".to_string(),
};
router.add_node(node, 100);
Source

pub fn try_add_node( &mut self, physical_node: T, virtual_node_count: i32, ) -> RocketMQResult<()>

Add a physical node to the hash ring, returning a typed error when virtual_node_count is negative.

Source

pub fn remove_node(&mut self, physical_node: &T)

Remove a physical node from the hash ring

This removes all virtual nodes associated with the given physical node.

§Arguments
  • physical_node - The physical node to remove
§Example
use rocketmq_common::common::consistenthash::ConsistentHashRouter;
use rocketmq_common::common::consistenthash::Node;

#[derive(Clone)]
struct ServerNode {
    name: String,
}

impl Node for ServerNode {
    fn get_key(&self) -> &str {
        &self.name
    }
}

let node = ServerNode {
    name: "node1".to_string(),
};
let mut router = ConsistentHashRouter::new(vec![node.clone()], 10);
router.remove_node(&node);
assert!(router.route_node("any-key").is_none());
Source

pub fn route_node_ref(&self, object_key: &str) -> Option<&T>

Route a key to a node on the hash ring

This method finds the nearest node in clockwise direction on the hash ring for the given key using consistent hashing algorithm.

§Arguments
  • object_key - The object key to find a nearest node for
§Returns
  • Some(T) - The physical node that the key should route to
  • None - If the ring is empty
§Example
use rocketmq_common::common::consistenthash::ConsistentHashRouter;
use rocketmq_common::common::consistenthash::Node;

#[derive(Clone)]
struct ServerNode {
    name: String,
}

impl Node for ServerNode {
    fn get_key(&self) -> &str {
        &self.name
    }
}

let nodes = vec![
    ServerNode {
        name: "node1".to_string(),
    },
    ServerNode {
        name: "node2".to_string(),
    },
];

let router = ConsistentHashRouter::new(nodes, 10);
let node = router.route_node("my-key");
assert!(node.is_some());
Source

pub fn route_node(&self, object_key: &str) -> Option<T>

Source

pub fn get_existing_replicas(&self, physical_node: &T) -> i32

Get the number of existing virtual nodes for a physical node

§Arguments
  • physical_node - The physical node to count replicas for
§Returns

The count of virtual nodes for the given physical node

Source

pub fn size(&self) -> usize

Get the total number of virtual nodes in the ring

§Returns

The total count of virtual nodes

Source

pub fn is_empty(&self) -> bool

Check if the ring is empty

§Returns

true if there are no nodes in the ring

Trait Implementations§

Source§

impl<T: Clone + Node + Clone> Clone for ConsistentHashRouter<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more