Skip to content

Instantly share code, notes, and snippets.

@raminfp
Created February 6, 2024 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raminfp/da5cab091f495c9ff1fe33d430614013 to your computer and use it in GitHub Desktop.
Save raminfp/da5cab091f495c9ff1fe33d430614013 to your computer and use it in GitHub Desktop.
use futures::executor::block_on;
use raft::prelude::*;
use std::thread;
use tokio::time::Duration;
#[tokio::main]
async fn main() {
// Create a Raft node configuration
let config = NodeConfig {
id: 1,
address: "127.0.0.1:5001".to_string(),
heartbeat_interval: Duration::from_secs(1),
election_timeout: Duration::from_secs(3),
};
// Create a Raft storage
let storage = MemStorage::new();
// Create three Raft nodes
let mut node1 = Node::new(&config, &storage);
let mut node2 = Node::new(&config, &storage);
let mut node3 = Node::new(&config, &storage);
// Start the Raft nodes in separate threads
let handle1 = thread::spawn(move || {
block_on(async {
node1.run().await.expect("Node 1 error");
})
});
let handle2 = thread::spawn(move || {
block_on(async {
node2.run().await.expect("Node 2 error");
})
});
let handle3 = thread::spawn(move || {
block_on(async {
node3.run().await.expect("Node 3 error");
})
});
// Simulate a client request and add it to the leader node
thread::sleep(Duration::from_secs(2));
if node1.is_leader() {
let client_request = "Value1".to_string();
let result = node1.append_entry(LogEntry::new(client_request.clone()));
// Wait for the request to be processed by all nodes
thread::sleep(Duration::from_secs(2));
// Print the result from each node
println!("Node 1: Client request result: {:?}", result);
println!("Node 2: Client request result: {:?}", node2.get_state_machine().get(&0));
println!("Node 3: Client request result: {:?}", node3.get_state_machine().get(&0));
}
// Wait for the nodes to finish
handle1.join().unwrap();
handle2.join().unwrap();
handle3.join().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment