Code Monkey home page Code Monkey logo

chatgpt-redis-service's Introduction

介绍

因为网络原因国内无法直接访问OpenAI的,所以我这里使用了Redis的发布订阅与OpenAI通信

部署

免费的Redis

客户端代码

package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/bwmarrin/snowflake"
	redis "github.com/redis/go-redis/v9"
)

const CHATGPT_CHANNEL = "chatGPT"


type Message struct {
	ChannelId string
	Request   string
}

func main() {
	rdb := redis.NewClient(&redis.Options{
		Addr:     "",
		Password: "", // 没有密码,默认值
		DB:       0,  // 默认DB 0
	})

	node, err := snowflake.NewNode(1)
	if err != nil {
		fmt.Println("Snowflake NewNode error:", err)
		return
	}

	channelId := node.Generate()

	// 定义一个Message结构体实例
	msg := Message{
		ChannelId: fmt.Sprintf("%d", channelId),
		Request:   "Hello",
	}

	// 将Message结构体序列化为JSON格式的字符串
	requestJson, err := json.Marshal(msg)
	if err != nil {
		fmt.Println("Json encode error:", err)
		return
	}

	err = rdb.Publish(context.Background(), CHATGPT_CHANNEL, requestJson).Err()
	if err != nil {
		fmt.Println("Publish error:", err)
		return
	}

	pubsub := rdb.Subscribe(context.Background(), msg.ChannelId)
	defer pubsub.Close()

	for msg := range pubsub.Channel() {
		fmt.Println(msg)
		break
	}
}

chatgpt-redis-service's People

Watchers

LuZhong avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.