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


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

查看所有标签

猜你喜欢:

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

Developer's Guide to Social Programming

Developer's Guide to Social Programming

Mark D. Hawker / Addison-Wesley Professional / 2010-8-25 / USD 39.99

In The Developer's Guide to Social Programming, Mark Hawker shows developers how to build applications that integrate with the major social networking sites. Unlike competitive books that focus on a s......一起来看看 《Developer's Guide to Social Programming》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

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

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具