arc_wrapped_client/
arc-wrapped-client.rs

1// Cadence - An extensible Statsd client for Rust!
2//
3// To the extent possible under law, the author(s) have dedicated all copyright and
4// related and neighboring rights to this file to the public domain worldwide.
5// This software is distributed without any warranty.
6//
7// You should have received a copy of the CC0 Public Domain Dedication along with this
8// software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
9
10// This example shows how you might use the Cadence client in your multithreaded
11// application by wrapping it in an Arc pointer. This allows you to access the
12// client from multiple threads.
13
14use cadence::prelude::*;
15use cadence::{NopMetricSink, StatsdClient};
16use std::sync::Arc;
17use std::thread;
18
19pub trait RequestHandler {
20    fn handle(&self) -> Result<(), String>;
21}
22
23pub struct ThreadedHandler {
24    metrics: Arc<dyn MetricClient + Send + Sync>,
25}
26
27impl ThreadedHandler {
28    fn new() -> ThreadedHandler {
29        ThreadedHandler {
30            metrics: Arc::new(StatsdClient::from_sink("example.prefix", NopMetricSink)),
31        }
32    }
33}
34
35impl RequestHandler for ThreadedHandler {
36    fn handle(&self) -> Result<(), String> {
37        let metrics_ref = self.metrics.clone();
38
39        let t = thread::spawn(move || {
40            let _ = metrics_ref.count("request.handled", 1);
41            println!("Hello from a threaded handler!");
42        });
43
44        t.join().unwrap();
45        Ok(())
46    }
47}
48
49fn main() {
50    let handler = ThreadedHandler::new();
51    handler.handle().unwrap();
52}