SNS Community Architecture design case sharing (II.)

Source: Internet
Author: User

Source: HTTP://WWW.JINHUSNS.COM/PRODUCTS/DOWNLOAD/?TYPE=XCJ

V. Schema usage notes > Caching > Usage instructions >

(a) Introduction to the Basic class library

    1. Icacheservice: The cache service interface for cached access calls;

Icacheservice Method Description:

Method name

Member Decoration

Description

Note

ADD (multiple parameters): void +1 overload

public static

Adding cache entries

Set (multiple parameters): void +1 overload

public static

Add or update a cache

If no corresponding cache entry is created, otherwise the update

Remove (Stringcachekey): void

public static

Remove Cache

Markdeletion (multiple parameters): void

public static

Identify as deleted

Clear (): void

public static

Empty cache

Get (String CacheKey): Object

public static

Get from cache

Get<t> (String cacheKey): T

public static

Get from cache

Getfromfirstlevel (Stringcachekey): Object

public static

Get from a layer of cache

Distributed cache in the case of distributed cache access

Getfromfirstlevel<t> (String cacheKey): T

public static

Get from a layer of cache

Distributed cache in the case of distributed cache access

1) Provide Tunynet.Caching.DefaultCacheService as the default implementation of Icacheservice;

    1. Cachesettingattribute: Used in the entity label cache related settings;

Cachesettingattribute Property Description:

property name

member Decoration

description

Remarks

Enablecache:bool

Public

Whether to enable caching

Only allow properties to be set in constructors

Expirationpolicy:

Entitycacheexpirationp Olicies

Public

Entity cache (entity body cache) expiration policy

 

propertynameofbody:string

Public

entity Body Cache Pair The property name to be applied (do not set this property if you do not need to store the entity body cache separately)

 

Propertynamesofarea: String

Public

Cache Partition property name (can be set multiple, comma delimited)

& nbsp;

    1. Realtimecachehelper: The main function is to increment the cache version number (generally without developer intervention) and auxiliary to obtain the cache CacheKey;

Realtimecachehelper Method Description:

Method name

Member Decoration

Description

Note

Getglobalversion (): Long

Public

List Cache Global version

Getentityversion (Objectprimarykey): Long

Public

Get cached version of entity

Getareaversion (multiple parameters): Long

Public

Get list Cache area version

Getcachekeyofentity (Object PrimaryKey): string

Public

Get the cachekey of an entity

Getlistcachekeyprefix (Multiple parameters): string

Public

Gets the prefix of the list cache CacheKey (for example: Abe3ds2sa90:8:)

Increaseentitycacheversion (object EntityId): void

Public

Increment entity cache (increment only if entity is updated)

Increaselistcacheversion (ientity entity): void

Public

Increment list cache version (increments only if entity is added and deleted)

Increaseareaversion (multiple parameters): void +2 overload

Public

Increment List Cache region version

(ii) Cache time expiration type

1. Preset The following expiration time (defined in Tunynet.Caching.CachingExpirationTypes);

Cache Age Type

Describe

Note

invariable

Permanently unchanged.

Stable

Stable data

Example: Resources.xml, area, application

Relativelystable

Relatively stable

For example: Permissions configuration, audit configuration, sensitive words, emoticons, site category, Information section, Information section Collection

Usualsingleobject

Common single objects

Examples: Users, groups, categories, tags, blog sections, albums section, forums, events

Usualobjectcollection

Common collection of objects

For example: A friend of a user

Singleobject

Single Object

For example: blog post, Post

ObjectCollection

Object collection

Example: Private data for paging

    1. The actual use of the current is absolute expiration time (for example: 5 minutes expired);
    2. Try not to set the specific expiration time directly when using the cache;
    3. You can configure an expiration time factor (Cacheexpirationfactor) that is used to uniformly provision the specific time corresponding to the preset expiration time type;

(iii) Cache configuration instructions

The cache service is registered through the DI container, for example:

Register Cache

Containerbuilder.register (c = new Defaultcacheservice (new Runtimememorycache (), 1.0F)). As<icacheservice> (). SingleInstance ();

    1. You can instantiate defaultcacheservice with different constructors to support distributed caching, or set the cache expiration factor, which will affect the cache expiration time of the preset in general;
    2. For performance consideration, it must be registered as a single case;

3. If the Icacheservice is implemented by itself, the same is registered to replace Defaultcacheservice;

(iv) Cache development considerations

    1. In a distributed cache scenario, the update cache must be explicitly called for update operations (Icacheservice.set ()), because the Web server and the cache server may be on different servers, rather than distributed caches, which can directly update the data obtained from the cache with the characteristics of the reference type. Without displaying the call cache update operation (Icacheservice.set ());
    2. All data that may require a distributed cache must support serialization/deserialization:

1) The entities to be cached must be labeled [Serializable];

2) Special data types must verify that serialization/deserialization is supported, for example, a type derived from dictionary<t key,t value> cannot be serialized directly;

3. Do not use Repository.gettopentities (Inttopnumber, Cachingexpirationtypescachingexpirationtypes, Func<string>g Etcachekey, Func<petapoco.sql>generatesql) is associated with Topnumber when setting cachekey, because no matter what the Topnumber value is, It will actually fetch up to secondarymaxrecords data and cache them. That is, different topnumber can share a single cache for increased cache usage, which in turn improves performance.

(v) cached annotations for entities

Use Cachesettingattribute to label entities so that most of the caching work is automatically processed repository.

    1. The cache policy for entities can be set through Expirationpolicy (currently mainly related to cache expiration time);
    2. You can set the entity body cache corresponding property name through Propertynameofbody;
    3. You can set the list partition cache related properties through Propertynamesofarea, you can set multiple partitions (that is, multiple attributes, separated by commas);

[Cachesetting (True, Expirationpolicy = entitycacheexpirationpolicies.normal, Propertynamesofarea = "UserId, CategoryId ", Propertynameofbody =" Body ")]

[Serializable]

Publicclassdiscussquestion:ientity

{

......

}

(vi) Use entity body cache

When the entity body is likely to be large, network traffic that increases operational efficiency and reduces the distributed cache stores the entity body cache separately and does not store that portion of content in the entity cache. Using the entity body cache, you need to follow these steps:

    1. Use Cachesettingattribute's propertynameofbody to label the entity, see the code example in the previous section;
    2. In the self-derived repository, write the method of obtaining the entity body, for example:

<summary>

Get discussquestion Content

</summary>

public string GetBody (long QuestionID)

{

String CacheKey = realtimecachehelper.getcachekeyofentitybody (questionid);

String BODY = cacheservice.get<string> (CacheKey);

if (BODY = = null)

{

Discussquestion question = database.singleordefault<discussquestion> (QuestionID);

BODY = question! = null? Question. Body:string. Empty;

Cacheservice.add (CacheKey, body, cachingexpirationtype.singleobject);

}

return body;

}

(vii) List cache usage

The main work of the list cache is the acquisition of CacheKey.

    1. 1. Using a version-free list cache

StringBuilder CacheKey = new StringBuilder (cachesetting.getlistcachekeyprefix (cacheversiontypes.none));

Cachekey.appendformat ("Ranking:sb-{0}", (int) sortby);

return cachekey.tostring ();

    1. 2. Using a version of the list cache

1) You can get the list cache CacheKey prefix by Realtimecachehelper, using the first method directly is the easiest way;

public string Getlistcachekeyprefix (Cacheversiontype cacheversiontype, String Areacachepropertyname, Object Areacachepropertyvalue);

2) When using a query condition class and requiring an instant cache, you can make the query conditional class implement Ilistcachesetting, for example:

<summary>

Discussquestion Query Condition Encapsulation

</summary>

public class Discussquestionquery:ilistcachesetting

{

Public Discussquestionquery (Cacheversiontypes cacheversiontype)

{

This.cacheversiontype = Cacheversiontype;

}

......

#region Ilistcachesetting Members

Private cacheversiontypes cacheversiontype = Cacheversiontypes.none;

<summary>

List Cache version settings

</summary>

Cacheversiontypesilistcachesetting.cacheversiontype

{

get {return cacheversiontype;}

}

private string areacachepropertyname = null;

<summary>

Cache partition Field Name

</summary>

public string Areacachepropertyname

{

get {return areacachepropertyname;}

set {areacachepropertyname = value;}

}

Private object areacachepropertyvalue = null;

<summary>

Cache partition Field values

</summary>

public Object Areacachepropertyvalue

{

get {return areacachepropertyvalue;}

set {Areacachepropertyvalue = value;}

}

#endregion

}

3) repository can be defined using the following code to obtain the CacheKey:

StringBuilder CacheKey = new StringBuilder (realtimecachehelper.getlistcachekeyprefix (query));

if (query. Userid.hasvalue)

Cachekey.appendformat ("userid-{0}:", query. Userid.value);

Cachekey.appendformat ("sb-{0}:", (int) query. SortBy);

return cachekey.tostring ();

4) construct the discussquestionquery using the following code in the service:

<summary>

Get the problem I created

</summary>

Public pagingdataset<discussquestion> getmyquestions (long userId, int pageIndex)

{

Discussquestionquery query = new Discussquestionquery (cacheversiontype.areaversion);

Query. Areacachepropertyname = "UserId";

Query. Areacachepropertyvalue = userId;

Query. UserID = userid;

return questionrepository.getquestions (query, Questionpagesize, PageIndex);

}

(eight) How to use attributes other than entities as partitions

When using attributes other than entities as partitions, it is not possible to rely on repository to automatically maintain the corresponding partition cache version, which needs to be controlled by the code itself.

    1. Write code to increment the partition cache version yourself, for example:

<summary>

Adding users to a set of roles

</summary>

public void addusertoroles (int userID, list<int> roleids)

{

var sql_delete = PetaPoco.Sql.Builder.Append ("Delete from tn_usersinroles where [email protected]", UserID);

list<petapoco.sql> sql_inserts = new list<petapoco.sql> ();

foreach (Var roleid in Roleids)

{

var Sql_insert = PetaPoco.Sql.Builder.Append ("INSERT into Tn_usersinroles (Userid,roleid) VALUES (@0,@1)", UserID, Roleid);

Sql_inserts. ADD (Sql_insert);

}

using (var scope = database.gettransaction ())

{

Database.execute (Sql_delete);

Database.execute (Sql_inserts);

Scope.complete ();

}

Increment cache partition version number (UserID)

realtimecachehelper.increaseareaversion ("userid", userid);

}

    1. Get CacheKey with Realtimecachehelper.getlistcachekeyprefix (), for example:

<summary>

Get the role of the user

</summary>

Public ienumerable<role> getrolesofuser (int userID)

{

String CacheKey = Realtimecachehelper.getlistcachekeyprefix (cacheversiontypes.areaversion, "userid", UserID);

ienumerable<role> roles = cacheservice.get<ienumerable<role>> (CacheKey);

if (roles = = null)

{

var sql = PetaPoco.Sql.Builder

. Select ("Roleid")

. From ("Tn_usersinroles")

. Where ("UserID = @0", userid);

ilist<object> roleids = database.fetchfirstcolumn (sql);

Rolerepository rolerepository = new Rolerepository ();

roles = Rolerepository.populateentitiesbyprimarykeys (Roleids);

Cacheservice.add (CacheKey, roles, cachingexpirationtypes.usualobjectcollection);

}

return roles;

}

Http://www.jinhusns.com/Products/Curriculum/?type=xcj

SNS Community Architecture design case sharing (II.)

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.