agingMap

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2021 License: MIT Imports: 6 Imported by: 1

README

agingMap

基于 sync.Map 的一个带过期时间的 Map

go get -u github.com/520MianXiangDuiXiang520/agingMap

使用

packege main

import (
    "github.com/520MianXiangDuiXiang520/agingMap"
    "time"
    "fmt"
)

func main() {
    // 每秒遍历 50%,过期删除
    // am := NewAgingMap()
    
    // 惰性删除
    // am := NewWithLazyDelete()
    
    am := NewBaseAgingMap(time.Second * 5, 0.7)
    keyChan := make(chan int64, 10)
    go func() {
        for {
            key := time.Now().UnixNano()
            keyChan <- key
            am.Store(key, 1, time.Second) 
        }
    }()
    for {
        key := <- keyChan
        val, ok := am.Load(key)
        if ok {
            fmt.Println(val)
        }
    }
}

Documentation

Overview

AgingMap 提供了一种时效性的并发安全的 Map

Copyright 2016 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AgingMap added in v0.0.2

type AgingMap struct {
	// contains filtered or unexported fields
}

func NewAgingMap

func NewAgingMap() *AgingMap

NewAgingMap 用来创建一个时效性的 Map. NewAgingMap 创建的 Map 每隔 1s 会随机检查 50% 的数据,如果检查到的项目过期 他们会被删除,如果想要控制检查速率和范围,请使用 NewBaseAgingMap, 如果不希望 主动检查,请使用 NewWithLazyDelete。

func NewBaseAgingMap

func NewBaseAgingMap(spec time.Duration, deleteScale float64) *AgingMap

NewBaseAgingMap 用来创建一个时效性的 Map. NewAgingMap 创建的 Map 每隔 spec 会随机检查 deleteScale 的数据,如果检查到的项目过期 他们会被删除,如果不希望主动检查,请使用 NewWithLazyDelete

deleteScale 应该是大于 0 小于 1 的小数,否则的话将使用默认值 0.5

func NewWithLazyDelete

func NewWithLazyDelete() *AgingMap

NewWithLazyDelete 用来创建一个惰性删除的时效 Map. 惰性删除是指只有在进行 Load 操作时 againMap 才会去判断某一项有没有过期, 如果过期了,它会被删除,所以如果某一项一直没有被读取,那他将永远不会被删除。 与之对应的是使用 NewAgingMap 创建 Map, 这类 Map 会有定时任务定时清理已经过期的项。

func (*AgingMap) Delete added in v0.0.2

func (am *AgingMap) Delete(key interface{})

Delete 用于删除 key 对应的键值对,不管他有没有过期。

Example
am := NewAgingMap()
am.Store("key", "value", time.Second)
am.Delete("key")
Output:

func (*AgingMap) Load added in v0.0.2

func (am *AgingMap) Load(key interface{}) (val interface{}, ok bool)

Load 类似于 LoadWithDeadline,但他舍弃了 deadline

Example
am := NewAgingMap()
ch := make(chan string, 10)
for i := 0; i < 10; i++ {
	go func(i int) {
		for {
			key := fmt.Sprintf("%d: %d", i, time.Now().UnixNano())
			ch <- key
			am.Store(key, i, time.Second)
			time.Sleep(time.Duration(rand.Int63n(2000)) * time.Millisecond)
		}
	}(i)
}
for i := 0; i < 10; i++ {
	go func(i int) {
		for {
			key := <-ch
			val, ok := am.Load(key)
			fmt.Println(val, ok)
		}
	}(i)
}
for {
	key := <-ch
	val, ok := am.Load(key)
	fmt.Println(val, ok)
}
Output:

func (*AgingMap) LoadOrStore added in v0.0.4

func (am *AgingMap) LoadOrStore(key, value interface{}, age time.Duration) (v interface{}, deadline float64, stored bool)

LoadOrStore key 存在直接返回,不存在存储 k, v

func (*AgingMap) LoadWithDeadline added in v0.0.2

func (am *AgingMap) LoadWithDeadline(key interface{}) (val interface{}, deadline float64, ok bool)

LoadWithDeadline 根据 key 返回三个值:val 表示 key 对应的 value, deadline 代表该键值对剩余的生存时间,单位秒,ok 表示 key 是否存在 如果 key 不存在,将会返回 nil, 0, false

func (*AgingMap) Range added in v0.0.2

func (am *AgingMap) Range(f func(k, v interface{}) bool)

Range 用来遍历 Map 中的键值对,遍历到的 k, v 将被赋值给 f 的两个参数 f 返回 false 时,遍历会结束,使用方法如下:

// am := NewAgingMap()
// // ...
// am.Range(func(k, v interface{}) bool {
//     fmt.Println(k, v)
//     return true
// }

func (*AgingMap) Store added in v0.0.2

func (am *AgingMap) Store(key, v interface{}, age time.Duration)

Store 用于向 Map 中存入一条数据,如果 key 已经存在,旧值将被新值覆盖。 age 用于指定该键值对的生存时长。

Example
am := NewAgingMap()
am.Store("key", "value", time.Second)
Output:

func (*AgingMap) TermLoadOrStore added in v0.0.4

func (am *AgingMap) TermLoadOrStore(key, value interface{}, age time.Duration,
	term TermFunc) (v interface{}, deadline float64, stored bool)

term 返回 true 则执行 Store,否则执行 Load

type Map

type Map struct {
	// contains filtered or unexported fields
}

Map is like a Go map[interface{}]interface{} but is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.

The Map type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content.

The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.

The zero Map is empty and ready for use. A Map must not be copied after first use.

func (*Map) Delete

func (m *Map) Delete(key interface{})

Delete deletes the value for a key.

func (*Map) Load

func (m *Map) Load(key interface{}) (value interface{}, ok bool)

Load returns the value stored in the map for a key, or nil if no value is present. The ok result indicates whether value was found in the map.

func (*Map) LoadOrStore

func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

func (*Map) Range

func (m *Map) Range(f func(key, value interface{}) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently, Range may reflect any mapping for that key from any point during the Range call.

Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.

func (*Map) ReadSize

func (m *Map) ReadSize() int

func (*Map) Store

func (m *Map) Store(key, value interface{})

Store sets the value for a key.

type TermFunc added in v0.0.4

type TermFunc func(val interface{}, ok bool) bool

Jump to

Keyboard shortcuts

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