snap

package
v2.22.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 9, 2024 License: MIT Imports: 2 Imported by: 0

README

Snap

The snap package in Go provides a thread-safe mechanism to manage and periodically refresh cached values using a custom refresh function.

It supports configurable refresh intervals and ensures that the value is always up-to-date without manual intervention.

This package is ideal for scenarios where you need to maintain a fresh state with minimal overhead.

Features

  • Thread-safe: Ensures safe access and updates in concurrent scenarios.
  • Configurable Refresh Interval: Allows you to specify how often the value should be refreshed.
  • Automatic Refresh: Automatically updates the cached value using a provided refresh function.

Usage

package main

import (
	"fmt"
	"time"

	"github.com/go-kratos-ecosystem/components/v2/snap"
)

type Config struct {
	Name string
}

func main() {
	s := snap.New(func() (*Config, error) {
		// get config from remote/datastore/...
		return &Config{
			Name: "test",
		}, nil
	}, snap.Interval[*Config](1000*time.Second))

	fmt.Print(s.Get()) // &{test} <nil>&
	fmt.Print(s.Get()) // &{test} <nil>&
	// after 1000 seconds
	fmt.Print(s.Get()) // &{test} <nil>& after refresh

	// refresh immediately
	s.Refresh()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option[T any] func(*Snap[T])

func Async added in v2.17.1

func Async[T any](async bool) Option[T]

func Interval

func Interval[T any](interval time.Duration) Option[T]

type Snap

type Snap[T any] struct {
	// contains filtered or unexported fields
}

func New

func New[T any](refresh func() (T, error), opts ...Option[T]) *Snap[T]

func (*Snap[T]) Get

func (s *Snap[T]) Get() T

func (*Snap[T]) Refresh

func (s *Snap[T]) Refresh() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL