golang的 端

要注意的是要先订阅回复,然后再发送请求。

package main

import (
	"github.com/go-redis/redis"
)

var wait = make(chan interface{})

func main() {
	client := redis.NewClient(&redis.Options{
		Addr:     "www.lastsweetop.com:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	pubsub := client.Subscribe("sayhello_rsp")
	defer pubsub.Close()

	pubsub.Receive();
	go func() {
		ch := pubsub.Channel();
		select {
		case channel := <-ch:
			println(channel.Payload)
			wait <- 1
		}
	}()
	println("hello rust")
	client.Publish("sayhello_req", "hello rust")

	<-wait
}

rust作为被调用端订阅请求,rust将订阅到消息通知和处理分开,并且做成多线程处理。

use std::sync::mpsc;
use std::thread;
use std::sync::Arc;
use std::sync::Mutex;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let client = redis::Client::open("redis://www.lastsweetop.com/")?;
    let mut con = client.get_connection()?;

    let mut pubsub = con.as_pubsub();
    pubsub.subscribe("sayhello_req")?;

    let (tx, rx) = mpsc::channel();
    let receiver = Arc::new(Mutex::new(rx));

    for _ in 1..10 {
        let con2 = client.get_connection()?;
        let rx_arc = Arc::clone(&receiver);

        thread::spawn(move || {
            loop {
                let message = rx_arc.lock().unwrap().recv().unwrap();
                println!("payload : {}", message);
                redis::cmd("PUBLISH").arg("sayhello_rsp").arg("hello go").execute(&con2);
            }
        });
    }

    loop {
        let msg = pubsub.get_message()?;
        let payload: String = msg.get_payload()?;
        tx.send(payload)?;
    }
}

当然反过来也一样,但是基本 go 做前端api业务,然后rust做具体的底层实现。