package concurrency

import (
    "time"

    v3 "github.com/coreos/etcd/clientv3"
    "golang.org/x/net/context"
)

const defaultSessionTTL = 60

// Session represents a lease kept alive for the lifetime of a client.
// Fault-tolerant applications may use sessions to reason about liveness.
type Session struct {
    client *v3.Client
    opts   *sessionOptions
    id     v3.LeaseID

    cancel context.CancelFunc
    donec  <-chan struct{}
}

// NewSession gets the leased session for a client.
func NewSession(client *v3.Client, opts ...SessionOption) (*Session, error) {
    ops := &sessionOptions{ttl: defaultSessionTTL, ctx: client.Ctx()}
    for _, opt := range opts {
        opt(ops)
    }

    resp, err := client.Grant(ops.ctx, int64(ops.ttl))
    if err != nil {
        return nil, err
    }
    id := v3.LeaseID(resp.ID)

    ctx, cancel := context.WithCancel(ops.ctx)
    keepAlive, err := client.KeepAlive(ctx, id)
    if err != nil || keepAlive == nil {
        return nil, err
    }

    donec := make(chan struct{})
    s := &Session{client: client, opts: ops, id: id, cancel: cancel, donec: donec}

    // keep the lease alive until client error or cancelled context
    go func() {
        defer close(donec)
        for range keepAlive {
            // eat messages until keep alive channel closes
        }
    }()

    return s, nil
}

// Client is the etcd client that is attached to the session.
func (s *Session) Client() *v3.Client {
    return s.client
}

// Lease is the lease ID for keys bound to the session.
func (s *Session) Lease() v3.LeaseID { return s.id }

// Done returns a channel that closes when the lease is orphaned, expires, or
// is otherwise no longer being refreshed.
func (s *Session) Done() <-chan struct{} { return s.donec }

// Orphan ends the refresh for the session lease. This is useful
// in case the state of the client connection is indeterminate (revoke
// would fail) or when transferring lease ownership.
func (s *Session) Orphan() {
    s.cancel()
    <-s.donec
}

// Close orphans the session and revokes the session lease.
func (s *Session) Close() error {
    s.Orphan()
    // if revoke takes longer than the ttl, lease is expired anyway
    ctx, cancel := context.WithTimeout(s.opts.ctx, time.Duration(s.opts.ttl)*time.Second)
    _, err := s.client.Revoke(ctx, s.id)
    cancel()
    return err
}

type sessionOptions struct {
    ttl int
    ctx context.Context
}

// SessionOption configures Session.
type SessionOption func(*sessionOptions)

// WithTTL configures the session's TTL in seconds.
// If TTL is <= 0, the default 60 seconds TTL will be used.
func WithTTL(ttl int) SessionOption {
    return func(so *sessionOptions) {
        if ttl > 0 {
            so.ttl = ttl
        }
    }
}

// WithContext assigns a context to the session instead of defaulting to
// using the client context. This is useful for canceling NewSession and
// Close operations immediately without having to close the client. If the
// context is canceled before Close() completes, the session's lease will be
// abandoned and left to expire instead of being revoked.
func WithContext(ctx context.Context) SessionOption {
    return func(so *sessionOptions) {
        so.ctx = ctx
    }
}

session.go的更多相关文章

  1. session实现购物车

    为实现简单的购物功能(购物车添加.账户查看.购物车商品删除.实时的购物商品数量及价格的计算显示.购物车商品数量可手动输入等),用session实现了一简单的以php语言为基础.连接MySQL数据库的购 ...

  2. Asp.net Core中使用Session

    前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. 元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Cor ...

  3. 懒加载session 无法打开 no session or session was closed 解决办法(完美解决)

           首先说明一下,hibernate的延迟加载特性(lazy).所谓的延迟加载就是当真正需要查询数据时才执行数据加载操作.因为hibernate当中支持实体对象,外键会与实体对象关联起来.如 ...

  4. 探索ASP.NET MVC5系列之~~~6.Session篇(进程外Session)

    其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.ht ...

  5. Nhibernate的Session管理

    参考:http://www.cnblogs.com/renrenqq/archive/2006/08/04/467688.html 但这个方法还不能解决Session缓存问题,由于创建Session需 ...

  6. nginx+iis+redis+Task.MainForm构建分布式架构 之 (redis存储分布式共享的session及共享session运作流程)

    本次要分享的是利用windows+nginx+iis+redis+Task.MainForm组建分布式架构,上一篇分享文章制作是在windows上使用的nginx,一般正式发布的时候是在linux来配 ...

  7. zookeeper源码分析之六session机制

    zookeeper中session意味着一个物理连接,客户端连接服务器成功之后,会发送一个连接型请求,此时就会有session 产生. session由sessionTracker产生的,sessio ...

  8. [转载]Cookie/Session的机制与安全

    Cookie和Session是为了在无状态的HTTP协议之上维护会话状态,使得服务器可以知道当前是和哪个客户在打交道.本文来详细讨论Cookie和Session的实现机制,以及其中涉及的安全问题. 因 ...

  9. 修改session垃圾回收几率

    <?php //修改session垃圾回收几率 ini_set('session.gc_probability','1'); ini_set('session.gc_divisor','2'); ...

  10. Nginx反向代理,负载均衡,redis session共享,keepalived高可用

    相关知识自行搜索,直接上干货... 使用的资源: nginx主服务器一台,nginx备服务器一台,使用keepalived进行宕机切换. tomcat服务器两台,由nginx进行反向代理和负载均衡,此 ...

随机推荐

  1. Mac OS X 10.10优胜美地如何完美接管iphone上的电话和短信

    自从今年苹果第一次的发布会上毛猫就特别注意这个功能,感觉特别Cool,特别方便.但直到今天毛猫才第一次成功测试出这个功能呀!虽然handoff功能还未测出来,但是觉得在mac上发短信和打电话也已经足够 ...

  2. 从零开始搭建基于CEFGlue的CB/S的winform项目

    基于CEF,用.net包装过的Xilium.CefGlue/3,基于此框架可以很方便在你的winform等C/S项目中搭建一个内建的浏览器 Chromium Embedded Framework (C ...

  3. react中需要用到【深度复制】的问题

    首先,说一下我所遇到的问题,我所做的项目是用的基于react的antd框架. 一张表格,里面的数据是从后台获取直接渲染,我点击修改按钮,在modal弹框中修改数据,但是没有点击确定,点击取消,发现页面 ...

  4. 温故而后知新——对ado.net中常用对象的一些解释

    在使用ado.net连接数据库获取数据,一般的步骤是: 1.设置好web.config    //用来设置服务器数据库的地址以及登录名密码 2.创建Connection对象    //用来创建访问数据 ...

  5. Aptana下Django1.6以后的项目模板结构改造

    Django1.6以后的manage.py放在项目包目录的根目录下,这种情况下在create app的app也在这个目录下面,由此可能导致app的名称有可能会和广大的内建包或者第三方包发生命名冲突,解 ...

  6. PHP实现单例模式和观察者模式

    单例模式的实现: PHP中单例模式常用在数据库连接部分,省掉了大量的new操作进而节省了很多资源.单例模式还可以用在全局配置类中. 单例模式,顾名思义就是说只有一个实例,这就要求防止外部随意实例化对象 ...

  7. Node笔记一

    什么是javascript? --脚本语言 --运行在浏览器中 --一般用来做客户端页面的交互 javascript运行环境 --运行在浏览器内核中的JS引擎 浏览器这种javascript可以做什么 ...

  8. 基于Cloudera Search设计数据灾备方案

    当实际项目上线到生产环境中,难以避免一些意外情况,如数据丢失.服务器停机等.对于系统的搜索服务来说,当遇到停机的情况意味着在停机这段时间内,用户都不能通过搜索的相关功能进行访问数据,停机意味着将这一段 ...

  9. Navicat永久激活步骤,激活工具,解决注册码无效的问题

    Navicat for MySQL是一套管理和开发MySQL或MariaDB的理想解决方案,支持单一程序,可同时连接到MySQL和MariaDB.这个功能齐备的前端软件为数据库管理.开发和维护提供了直 ...

  10. 妙用this关键字

    妙用this关键字 ## this关键字一般this关键字都是指的是对象的本身,在类的所有方法.构造器都可以拿到this引用,这是jvm"偷偷"帮我们传递进来的引用,指向调用方法对 ...