国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home WeChat Applet WeChat Development WeChat public platform development: solving user context (Session) issues

WeChat public platform development: solving user context (Session) issues

Feb 27, 2017 pm 01:08 PM
Micro-channel public platform

Overview

Due to the special mechanism of the WeChat public platform, all information is forwarded by the WeChat server, so the server cannot use Session to manage the context of the user session.

For this reason, Senparc.WeiXin.MP SDK adds a context module and integrates it into MessageHandler.

WeixinContext

WeixinContext is a container for all single user context (MessageContext) entities (tentatively called the global context). WeixinContext itself is not a static class, which means you can create multiple context entities in the same application.

At the same time, a static WeixinContext instance is put into MessageHandler, so the WeixinContext in all subclasses derived from MessageHandler in all projects is unique and global (Note: TM is Classes that implement IMessageContext, including MessageContext already provided in the SDK).

So in any instance that implements MessageHandler (such as MyMessageHandler), we can access an object whose type and name are WeixinContext.

WeixinContext is used to save the user's context (MessageContext) and provides a series of methods. The main methods include:

///


/// Reset all context parameters, all records will be cleared
///

public void Restore()
{
...
}

/// & lt; Summary & GT;
/// Get MESSAGECONTEXT, if it does not exist, return null
/// It is to operate the TM queue, remove expired information in time, and move the latest active objects to the end
///
/// Username ( OpenId)
?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????## ///
/// Get MessageContext
///

/// Username (OpenId)< ;/param>
/// True: If the user does not exist, create an instance and return the latest instance
/// False: The user is stored in, Then return null
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

## ///
/// Get the MessageContext. If it does not exist, initialize one using the requestMessage information and return the original instance
///

///
public TM GetMessageContext(IRequestMessageBase requestMessage)
{
...
}

/// /// Get the MessageContext. If it does not exist, initialize one using requestMessage information and return the original instance
///
///
public TM GetMessageContext(IResponseMessageBase responseMessage)
{
? ? ? ? ...
? ? }

? ? ///
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? to ? ?//

/// Request information
public void InsertMessage(IRequestMessageBase requestMessage)
{
...
}

?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????">Response message
public void InsertMessage(IResponseMessageBase responseMessage)
{
...
}

///
/// Get the latest request data, if it does not exist, return Null
///

/// Username (OpenId)< /param>
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????/
/// Get the latest response data, if it does not exist, return Null
///

///
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

WeixinContext has two objects used to store user context: MessageCollection and MessageQueue.

The element collections in these two objects overlap, but the MessageQueue sorts the elements so that the top expired context can be processed in a timely manner.

ExpireMinutes is used to define the context time validity period, the default is 90 minutes. You can set a parameter anywhere in the program and it will take effect immediately.

PS: The logic of deleting expired data in MessageQueue operates with extremely high efficiency. There is no need to consider CPU usage and object conflicts (whether the additional verification time times out) during regular development.

MessageContext

MessageContext is used to save the context information of a single user and is stored in the MessageCollection and MessageQueue objects of WeixinContext. IMessageContext is defined as follows:

/// <summary>
/// 微信消息上下文(單個用戶)接口
/// </summary>
/// <typeparam name="TRequest">請求消息類型</typeparam>
/// <typeparam name="TResponse">響應消息類型</typeparam>
public interface IMessageContext<TRequest,TResponse>
    where TRequest : IRequestMessageBase
    where TResponse : IResponseMessageBase
{
    /// <summary>
    /// 用戶名(OpenID)
    /// </summary>
    string UserName { get; set; }
    /// <summary>
    /// 最后一次活動時間(用戶主動發(fā)送Resquest請求的時間)
    /// </summary>
    DateTime LastActiveTime { get; set; }
    /// <summary>
    /// 接收消息記錄
    /// </summary>
    MessageContainer<TRequest> RequestMessages { get; set; }
    /// <summary>
    /// 響應消息記錄
    /// </summary>
    MessageContainer<TResponse> ResponseMessages { get; set; }
    /// <summary>
    /// 最大儲存容量(分別針對RequestMessages和ResponseMessages)
    /// </summary>
    int MaxRecordCount { get; set; }
    /// <summary>
    /// 臨時儲存數(shù)據(jù),如用戶狀態(tài)等,出于保持.net 3.5版本,這里暫不使用dynamic
    /// </summary>
    object StorageData { get; set; }
 
    /// <summary>
    /// 用于覆蓋WeixinContext所設置的默認過期時間
    /// </summary>
    Double? ExpireMinutes { get; set; }
 
    /// <summary>
    /// AppStore狀態(tài),系統(tǒng)屬性,請勿操作
    /// </summary>
    AppStoreState AppStoreState { get; set; }
 
    event EventHandler<WeixinContextRemovedEventArgs<TRequest, TResponse>> MessageContextRemoved;
 
    void OnRemoved();
}

You can create your own class according to your own needs, implement this interface, and be used by WeixinContext. Of course, if your requirements are not so special and you are lazy, the SDK provides a default MessageContext implementation:

/// <summary>
/// 微信消息上下文(單個用戶)
/// </summary>
public class MessageContext<TRequest,TResponse>: IMessageContext<TRequest, TResponse>
    where TRequest : IRequestMessageBase
    where TResponse : IResponseMessageBase
{
    private int _maxRecordCount;
 
    public string UserName { get; set; }
    public DateTime LastActiveTime { get; set; }
    public MessageContainer<TRequest> RequestMessages { get; set; }
    public MessageContainer<TResponse> ResponseMessages { get; set; }
    public int MaxRecordCount
    {
        get
        {
            return _maxRecordCount;
        }
        set
        {
            RequestMessages.MaxRecordCount = value;
            ResponseMessages.MaxRecordCount = value;
 
            _maxRecordCount = value;
        }
    }
    public object StorageData { get; set; }
 
    public Double? ExpireMinutes { get; set; }
 
    /// <summary>
    /// AppStore狀態(tài),系統(tǒng)屬性,請勿操作
    /// </summary>
    public AppStoreState AppStoreState { get; set; }
 
    public virtual event EventHandler<WeixinContextRemovedEventArgs<TRequest, TResponse>> MessageContextRemoved = null;
 
    /// <summary>
    /// 執(zhí)行上下文被移除的事件
    /// 注意:此事件不是實時觸發(fā)的,而是等過期后任意一個人發(fā)過來的下一條消息執(zhí)行之前觸發(fā)。
    /// </summary>
    /// <param name="e"></param>
    private void OnMessageContextRemoved(WeixinContextRemovedEventArgs<TRequest, TResponse> e)
    {
        EventHandler<WeixinContextRemovedEventArgs<TRequest, TResponse>> temp = MessageContextRemoved;
 
        if (temp != null)
        {
            temp(this, e);
        }
    }
 
    /// <summary>
    ///
    /// </summary>
    /// <param name="maxRecordCount">maxRecordCount如果小于等于0,則不限制</param>
    public MessageContext(/*MessageContainer<IRequestMessageBase> requestMessageContainer,
        MessageContainer<IResponseMessageBase> responseMessageContainer*/)
    {
        /*
         * 注意:即使使用其他類實現(xiàn)IMessageContext,
         * 也務必在這里進行下面的初始化,尤其是設置當前時間,
         * 這個時間關系到及時從緩存中移除過期的消息,節(jié)約內存使用
         */
 
        RequestMessages = new MessageContainer<TRequest>(MaxRecordCount);
        ResponseMessages = new MessageContainer<TResponse>(MaxRecordCount);
        LastActiveTime = DateTime.Now;
    }
 
    public virtual void OnRemoved()
    {
        var onRemovedArg = new WeixinContextRemovedEventArgs<TRequest, TResponse>(this);
        OnMessageContextRemoved(onRemovedArg);
    }
}

The above code is easy to understand based on the comments. What needs to be explained is StorageData. This is a container used to store any data related to the user context. WeixinContext and IMessageContext do not have any reference to it. It is entirely up to the developer to determine the content (such as which step the user has taken, or some important location information, etc. etc.), similar to the role of Session.

The above MessageContext class has provided relatively complete common message processing methods and can be used directly. If you have more special needs and need to customize MessageContext, it is recommended to use this class as the base class to make necessary rewrites. For example, the following is a custom context class:

public class CustomMessageContext : MessageContext<IRequestMessageBase,IResponseMessageBase>
{
    public CustomMessageContext()
    {
        base.MessageContextRemoved += CustomMessageContext_MessageContextRemoved;
    }
 
    /// <summary>
    /// 當上下文過期,被移除時觸發(fā)的時間
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void CustomMessageContext_MessageContextRemoved(object sender, Senparc.Weixin.Context.WeixinContextRemovedEventArgs<IRequestMessageBase,IResponseMessageBase> e)
    {
        /* 注意,這個事件不是實時觸發(fā)的(當然你也可以專門寫一個線程監(jiān)控)
         * 為了提高效率,根據(jù)WeixinContext中的算法,這里的過期消息會在過期后下一條請求執(zhí)行之前被清除
         */
 
        var messageContext = e.MessageContext as CustomMessageContext;
        if (messageContext == null)
        {
            return;//如果是正常的調用,messageContext不會為null
        }
 
        //TODO:這里根據(jù)需要執(zhí)行消息過期時候的邏輯,下面的代碼僅供參考
 
        //Log.InfoFormat("{0}的消息上下文已過期",e.OpenId);
    }
}

The above CustomMessageContext_MessageContextRemoved() method will be Triggered when a user's context is cleared, you can add the code you need. In addition, you can also override methods such as OnRemoved() in accumulation, or add other attributes and methods.

For more articles related to WeChat public platform development: solving user context (Session) issues, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276