golang通过redis调用rust

栏目: 编程语言 · Rust · 发布时间: 6年前

内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/89375879

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/89375879

golang的 redis

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

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做具体的底层实现。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

沸騰15年

沸騰15年

林軍 / 商周出版 / 2010年09月19日 / NTD:430元

從一九九五年到二○○九年,中國互聯網崛起、發展和壯大。 在短短十五年間 產生了十五家市值超過十億的上市公司 這些前仆後繼的先行者 不但用網際網路創造了歷史,也改寫了自己的財富路徑。 這本關於中國互聯網產業歷史的書,脈絡清晰、生動鮮明地把一大批創業者的形象和他們的動人故事呈現在讀者眼前,值得一讀。 ——中國互聯網協會理事長、中國科協副主席 胡啟?? 林軍這本......一起来看看 《沸騰15年》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具