ASP. NET Core uses Redis and Protobuf for Session caching and redisprotobuf

Source: Internet
Author: User
Tags redis cluster

ASP. NET Core uses Redis and Protobuf for Session caching and redisprotobuf

Reference page:

Http://www.yuanjiaocheng.net/ASPNET-CORE/newproject.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/project-layout.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/projectjson.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-configuration.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-middleware.html

Preface

The previous blog introduces how to use middleware in asp.net core and how to customize middleware. Redis is also used in the project, so this article describes how to use Redis for resource caching and Session caching in asp.net core. If you think it is helpful to you, click [recommendation ].

Directory
  • Redis Introduction
  • Introduction to asp.net core Session
  • Redis & Session instances
  • Session usage
  • Use Protobuf to add extension methods to the Session
Redis Introduction

The following is an introduction to the official Redis Website:

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

Redis is an open-source (based on the BSD license), memory data storage structure, commonly used as a database, cache, and message queue. It supports query of strings, hash tables, lists, sets, sorting set ranges, bitmaps, hyperlogs radius, and geospatial indexes and queries. Redis has built-in master-slave connections, Lua scripts, LRU recovery, transactions, and different levels of file persistence, and provides master-slave switchover and automatic partitioning of clusters to ensure high availability.

I will directly open the portal for Redis's in-depth introduction, which is not the focus of this article, but I have sorted it out for you. Thank you for the following:

Redis high availability deployment and monitoring: http://blog.sina.com.cn/s/blog_75ad98f30101fwqj.html
Redis master-slave connection: http://www.tuicool.com/articles/fAnYFb
Redis transaction: http://redisbook.readthedocs.io/en/latest/feature/transaction.html
Redis memory recycling LRU: http://www.open-open.com/lib/view/open1427547789059.html
Redis Data Persistence: http://qifuguang.me/2015/10/13/Redis%E6%8C%81%E4%B9%85%E5%8C%96/

After learning the above knowledge, it should not be a problem to cope with Redis questions during use and interview.

Introduction to asp.net core session

Session itself is a difficult term to explain. In http, session represents a session process between the server and the browser. This process may be sustained or interrupted.

Sessions in asp.net core are provided to us as middleware.

Let's take a look at the usage:
First, add the NuGet package of the sessionMicrosoft.AspNetCore.Http.AbstractionsTo the projectstartup.csFileConfigureServices(IServiceCollection services)Function, useapp.UseSession()Andapp.UseCaching()To use the session.

// Inject cacheing before using the session, because the session depends on the cache for storage services. AddCaching (); services. AddSession ();

After a session is added, you need to store the session. You can use memory storage or other custom storage, such as redis or SQL Server.

// Important: session registration must be performed before UseMvc, because the app is used in MVC. useSession (); app. useMvc (routes => {routes. mapRoute (name: "default", template: "{controller}/{action}/{id ?} ", Defaults: new {controller =" Home ", action =" Index "});});
Redis & Session instances

To use Redis in the Session, you only needservices.AddCaching();Changeservices.AddDistributedRedisCache();As shown in the following figure:

Services. addDistributedRedisCache (option => {// redis database connection string option. configuration = Configuration. getConnectionString ("RedisConnection"); // redis Instance name option. instanceName = "master ";});
Session usage

In the MVC Controller of asp.net core, you canHttpContext.SessionTo obtain the Session object.

If you do not need to use Session in the Controller, you can useIHttpContextAccessorThis interface obtains the Session through injection.

The following describes how to use Session in Controller.Microsoft.AspNetCore.HttpSpace:

public class HomeController : Controller{    public IActionResult Index()    {         HttpContext.Session.SetString("Test", "Ben Rules!");        return View();    }    public IActionResult About()    {        ViewBag.Message = HttpContext.Session.GetString("Test");        return View();    }}

The Session is used in other places except the Controller:

public class SomeOtherClass{    private readonly IHttpContextAccessor _httpContextAccessor;    private ISession _session => _httpContextAccessor.HttpContext.Session;    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)    {        _httpContextAccessor = httpContextAccessor;    }    public void TestSet()    {        _session.SetString("Test", "Ben Rules!");    }    public void TestGet()    {        var message = _session.GetString("Test");    }}
Use Protobuf to add extension methods to the Session

By default, we can only storebyte[]In our Session, this makes it inconvenient for us to use.Microsoft.HttpCore.ExtensionMicrosoft provides the SetString, SetInt32, GetString, and GetInt32 methods. However, in many cases, we need to use Session to store an object, in this case, you need to add an extension method to the Session.

To pursue efficiency and performance, we chose Google's Protobuf serialization component instead of Json. Net. Protobuf is much more efficient than XML or Json in terms of performance.

Introduce In the Nuget packageprotobuf-net:

public static class SessionExtensions{        public static T Get<T>(this ISession session, string key) where T : class {            byte[] byteArray = null;            if (session.TryGetValue(key, out byteArray)) {                using (var memoryStream = new MemoryStream(byteArray)) {                    var obj = ProtoBuf.Serializer.Deserialize<T>(memoryStream);                    return obj;                }            }            return null;        }        public static void Set<T>(this ISession session, string key, T value) where T : class {            try {                using (var memoryStream = new MemoryStream()) {                    ProtoBuf.Serializer.Serialize(memoryStream, value);                    byte[] byteArray = memoryStream.ToArray();                    session.Set(key, byteArray);                }            }            catch (Exception) {                throw;            }                   }}

To use Protobuf-net for serialization, you must mark the serialized object as [ProtoContract] [ProtoMember.

Ps: Current Redis ExtensionMicrosoft.Extensions.DependencyInjectionThe followingAddDistributedRedisCacheRC2 is not supported yet. You can go to github to search for the source code, add it to the project, or leave a mailbox. I will send it to you.

Address: http://www.cnblogs.com/savorboard/p/5592948.html
Author's blog: Savorboard
Reprinted. Please keep the source

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.