Giter Club home page Giter Club logo

grq's Introduction

grq

Go PkgGoDev Go Report Card

Package grq implements persistent, thread and cross process safe task queue, that uses redis as backend. It should be used, when RabbitMQ is too complicated, and MQTT is not enough (because it cannot cache messages), and BeanStalkd is classic from 21 september of 2007 year, that is hard to find in many linux distros.

GRQ means Golang Redis Queue.

Advertisement

You can support development of this module by sending money directly to author https://www.tinkoff.ru/rm/ostroumov.anatoliy2/4HFzm76801/

Simple task publisher

package main

import (
	queue "github.com/vodolaz095/grq"

	"log"
	"time"
)

type task struct {
	Payload string
}

func (t task) String() string {
	return t.Payload
}

func main() {
	q, err := queue.New("test")
	if err != nil {
		log.Fatalf("%s : while connecting to redis", err)
	}

	for t := range time.NewTicker(time.Second).C {
		err = q.Publish(task{Payload: t.Format(time.Stamp)})
		if err != nil {
			log.Fatalf("%s : while publishing task", err)
		}
		log.Println("Task published!")
	}
}

Simple task consumer

package main

import (
	queue "github.com/vodolaz095/grq"
	"log"
	"time"
)

func main() {
	q, err := queue.New("test")
	if err != nil {
		log.Fatalf("%s : while connecting to redis", err)
	}
	q.SetHeartbeat(100 * time.Millisecond)

	go func() {
		log.Println("Preparing to stop consuming")
		time.Sleep(time.Second)
		log.Println("Stopping consuming...")
		err := q.Cancel()
		if err != nil {
			log.Fatalf("%s : while closing redis task queue", err)
		}
		log.Println("Consuming stopped")
	}()

	tasks, err := q.Consume()
	if err != nil {
		log.Fatalf("%s : error consuming", err)
	}

	for t := range tasks {
		log.Printf("Task with payload >>>%s<<< received", t)
	}
	log.Printf("Consumer \"test\" was Canceled")
}

Big example

package main

import (
    "context"
	"fmt"
	"log"
	"time"

	"github.com/vodolaz095/grq"
)

func main() {
	var redisConnectionString = grq.DefaultConnectionString
	log.Printf("Dialing redis via %s", redisConnectionString)

	// creating publisher and consumer, utilizing same `example` queue

	publisher, err := grq.NewFromConnectionString("example", redisConnectionString)
	if err != nil {
		log.Fatalf("%s : while making publisher", err)
	}
    publisher.Context = context.Background() // by default, context is TODO, but you can change it, if required
	consumer, err := grq.NewFromConnectionString("example", redisConnectionString)
	if err != nil {
		log.Fatalf("%s : while making consumer", err)
	}

	go func() {
		// We start consumer here in different subroutine
		consumer.SetHeartbeat(10 * time.Millisecond)
		// if consumer did not received notifications for new tasks in example queue
		// for 10 milliseconds, it will try to get new messages by itself
		feed, err := consumer.Consume()
		if err != nil {
			log.Fatalf("%s : while making consumer", err)
		}
		for msg := range feed {
			// reveal, how many messages are left in queue
			n, err := consumer.Count()
			if err != nil {
				log.Fatalf("%s : while counting messages left", err)
			}
			// message consumed
			log.Printf("Message received: %s. Messages left %v", msg, n)
		}
	}()

	// we send tasks via publisher, anything that can be stringified by fmt.Sprint will do the trick
	err = publisher.Publish("message 1")
	if err != nil {
		log.Fatalf("%s : while publishing message 1", err)
	}
	err = publisher.Publish(time.Now())
	if err != nil {
		log.Fatalf("%s : while publishing message 2", err)
	}
	err = publisher.Publish(fmt.Errorf("errors can be stringified, so it will do the trick"))
	if err != nil {
		log.Fatalf("%s : while publishing message 3", err)
	}
	// wait for consumer to process all
	time.Sleep(time.Second)
	// consumer is stopped, but we can still send messages to queue
	err = consumer.Cancel()
	if err != nil {
		log.Fatalf("%s : canceling consumer", err)
	}

	// this message will be saved in queue, but not consumed
	err = publisher.Publish(10)
	if err != nil {
		log.Fatalf("%s : while publishing message 3", err)
	}

	payload, found, err := publisher.GetTask()
	if err != nil {
		log.Fatalf("%s : while getting message 3 from queue", err)
	}
	if !found {
		fmt.Println("where is our task? is it gone?")
	}
	fmt.Printf("Message 3 payload is %s\n", payload)

	_, found, err = publisher.GetTask()
	if err != nil {
		log.Fatalf("%s : while getting nothing from queue", err)
	}
	if found {
		fmt.Println("there is task present???")
	} else {
		fmt.Println("nothing left in the queue")
	}

	// publisher connection to redis database is closed
	err = publisher.Close()
	if err != nil {
		log.Fatalf("%s : while closing publisher", err)
	}

	// consumer connection to redis database is closed
	err = consumer.Close()
	if err != nil {
		log.Fatalf("%s : while closing consumer", err)
	}
}

Protocol definition

Protocol is very simple, it can be used by your favourite redis client, including official redis-cli. Publishing task to queue taskQueue1 with payload 1419719 can be performed by redis command lpush:

$ redis-cli lpush taskQueue1 1419719

If we want task to be executed first, it can be added to queue via rpush:

$ redis-cli rpush taskQueue1 1419719

If we want to notify consumers that task is published, and we don't want to wait, when consumers internal timers triggers, we can send notification that there is event in queue via publish redis command.

$ redis-cli publish taskQueue1 anythingAsPayloadBecauseItIsIgnored

If we want to consume an event from a queue, we can use lpop:

$ redis-cli lpop taskQueue1

and payload of 1419719 will be returned.

If we want to receive notification, when there are new messages in the queue, we can subscribe to this kind of messages easily:

$ redis-cli SUBSCRIBE "redisQueue/testHeartBeat"

License

The MIT License (MIT)

Copyright (c) 2020 Ostroumov Anatolij

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

grq's People

Contributors

vodolaz095 avatar

Stargazers

 avatar

Watchers

 avatar  avatar  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.