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


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

查看所有标签

猜你喜欢:

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

Building Websites with Joomla!

Building Websites with Joomla!

H Graf / Packt Publishing / 2006-01-20 / USD 44.99

This book is a fast paced tutorial to creating a website using Joomla!. If you've never used Joomla!, or even any web content management system before, then this book will walk you through each step i......一起来看看 《Building Websites with Joomla!》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具