In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how the development of Wechat public platform solves the problem of user context Session. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Overview
Due to the special mechanism of Wechat public platform, all the information is forwarded by Wechat server, so the server can not use Session to manage the context of user sessions.
For this reason, Senparc.WeiXin.MP SDK adds contextual modules and integrates them into MessageHandler.
WeixinContext
WeixinContext is the container (temporarily called global context) for all individual user context (MessageContext) entities. WeixinContext itself is not a static class, which means that you can create multiple contextual entities in the same application.
At the same time, a static instance of WeixinContext is put into MessageHandler, so the WeixinContext in subclasses derived from MessageHandler in all projects is unique and global (note: TM is a class that implements IMessageContext, including MessageContext already provided in SDK).
So in any instance that implements MessageHandler (called MyMessageHandler, for example), we can access an object with both type and name WeixinContext.
WeixinContext is used to save the context of the user (MessageContext) and provides a series of methods, including:
/ reset all context parameters, all records will be cleared / public void Restore () {.} / get MessageContext, if it does not exist, return null / / this method is more important to operate the TM queue and remove expired information in time. And move the most recently active object to the tail / user name (OpenId) / private TM GetMessageContext (string userName) {.} / get MessageContext / user name (OpenId) / True: if the user does not exist, create an instance And return the latest instance / False: user storage, return null / private TM GetMessageContext (string userName, bool createIfNotExists) {.} / get MessageContext. If it does not exist, initialize one with requestMessage information And return the original instance / public TM GetMessageContext (IRequestMessageBase requestMessage) {.} / to get the MessageContext. If it does not exist, initialize one with the requestMessage information And return the original instance / public TM GetMessageContext (IResponseMessageBase responseMessage) {.} / record request information / request information public void InsertMessage (IRequestMessageBase requestMessage) {.} / Record response information / response information public void InsertMessage (IResponseMessageBase responseMessage) {.} / get the latest request data If it does not exist, return Null / user name (OpenId) / public IRequestMessageBase GetLastRequestMessage (string userName) {.} / to get the latest response data, if it does not exist Return Null / user name (OpenId) / public IResponseMessageBase GetLastResponseMessage (string userName) {.}
There are two objects in WeixinContext for storing user context: MessageCollection and MessageQueue.
The set of elements in the two objects coincides, but MessageQueue sorts the elements to get rid of the out-of-date context at the top in a timely manner.
ExpireMinutes is used to define the context time validity period, which defaults to 90 minutes. You can set a parameter anywhere in the program and take effect immediately.
The logic of deleting expired data in PS:MessageQueue operates with great efficiency, and regular development does not need to consider the problems of CPU occupation and object conflicts (whether the extra check time is timed out).
MessageContext
MessageContext is used to save the context information of a single user, which is stored in the MessageCollection and MessageQueue objects of WeixinContext. IMessageContext is defined as follows:
/ / Wechat message context (single user) API / request message type / response message type public interface IMessageContext where TRequest: IRequestMessageBase where TResponse: IResponseMessageBase {/ username (OpenID) / string UserName {get; set } / Last active time (time when the user actively sent the Resquest request) / DateTime LastActiveTime {get; set;} / receive message logging / MessageContainer RequestMessages {get; set;} / response message logging / MessageContainer ResponseMessages {get; set } / maximum storage capacity (for RequestMessages and ResponseMessages, respectively) / int MaxRecordCount {get; set;} / temporarily store data, such as user status, etc. In order to maintain the .net 3.5 version, dynamic / object StorageData {get; set is not used here } / is used to override the default expiration time set by WeixinContext / Double? ExpireMinutes {get; set;} / AppStore status, system properties, do not operate / AppStoreState AppStoreState {get; set;} event EventHandler MessageContextRemoved; void OnRemoved ();}
You can create your own classes according to your needs, implement this interface, and be used by WeixinContext. Of course, if your requirements are not so special and you are lazy, SDK provides a default MessageContext implementation:
/ Wechat message context (single user) / public class MessageContext: IMessageContext where TRequest: IRequestMessageBase where TResponse: IResponseMessageBase {private int _ maxRecordCount; public string UserName {get; set;} public DateTime LastActiveTime {get; set;} public MessageContainer RequestMessages {get; set;} public MessageContainer 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;} / AppStore status, system property, do not operate / public AppStoreState AppStoreState {get; set;} public virtual event EventHandler MessageContextRemoved = null; / execution context removed event / / Note: this event is not triggered in real time, but before the execution of the next message sent by anyone after expiration. / private void OnMessageContextRemoved (WeixinContextRemovedEventArgs e) {EventHandler temp = MessageContextRemoved; if (temp! = null) {temp (this, e) }} / maxRecordCount if less than or equal to 0, then do not restrict public MessageContext (/ * MessageContainer requestMessageContainer, MessageContainer responseMessageContainer*/) {/ * * Note: even if other classes are used to implement IMessageContext, * be sure to initialize here, especially to set the current time * this time is related to timely removal of expired messages from the cache, saving memory usage * / RequestMessages = new MessageContainer (MaxRecordCount) ResponseMessages = new MessageContainer (MaxRecordCount); LastActiveTime = DateTime.Now;} public virtual void OnRemoved () {var onRemovedArg = new WeixinContextRemovedEventArgs (this); OnMessageContextRemoved (onRemovedArg);}}
The above code is easy to understand according to the comments, and it needs to be explained that it is StorageData. This is a container for storing any data related to the user's context. WeixinContext and IMessageContext do not make any references to it, and it is entirely up to the developer to decide the contents (such as which step the user executes, or some more important location information, etc.), similar to the role of Session.
The above MessageContext class has provided a relatively complete method of commonly used message processing, which can be used directly. If you have more special requirements and need to customize MessageContext, it is recommended to use this class as the base class for necessary rewriting. For example, the following is a custom context class:
Public class CustomMessageContext: MessageContext {public CustomMessageContext () {base.MessageContextRemoved + = CustomMessageContext_MessageContextRemoved } / void CustomMessageContext_MessageContextRemoved (object sender, Senparc.Weixin.Context.WeixinContextRemovedEventArgs e) {/ * Note that this event is not triggered in real time (of course, you can also write a thread monitor) * to improve efficiency, according to the algorithm in WeixinContext The expired message here will be cleared before the next request is executed after the expiration * / var messageContext = e.MessageContext as CustomMessageContext If (messageContext = = null) {if return;// is a normal call, messageContext will not be null} / / TODO: the logic of message expiration is executed here as needed. The following code is for reference only / / Log.InfoFormat ("message context of {0} has expired", e.OpenId);}}
The CustomMessageContext_MessageContextRemoved () method above triggers when a user's context is cleared, in which you can add the code you need. In addition, you can override methods such as OnRemoved () in the accumulation, or add other properties and methods.
Thank you for reading! This is the end of the article on "how to solve the problem of user context Session in the development of Wechat public platform". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.