Use Spring. Net technology to create a switchable distributed cache read/write class

Source: Internet
Author: User

Use Spring.Net technology to create switchable Memcached distributed cache read and write classes

Memcached is a high-performance distributed memory object cache system. Because it works in memory, the read and write rate is higher than that of the database. It has the same advantages as Radis. "Configuration and Use under Windows" has introduced its configuration and use on Windows.
 
Create a new ICacheWriter class-the interface of CacheWriter, so that the cache read / write mode can be switched through the configuration file. For example, cache read / write can also be performed through httpruntime.cache.
code show as below:
 
Copy code
1 public interface ICacheWriter
2 {
3 void Set (string key, object value, DateTime exp);
4 void Set (string key, object value);
5 object Get (string key);
6}
Copy code
Add the memcached server address under the appSettings node in the configuration file. E.g:
<add key = "memcachedServer" value = "127.0.0.1:11211" />
Create a new MemcachedWriter class with the following code:
Copy code
 1 // Singleton mode
 2 private static readonly MemcachedClient client;
 3 static MemcachedWriter ()
 4 {
 5
 6 string [] servers = ConfigurationManager.AppSettings ["memcachedServer"]. Split (new char [] {','}, StringSplitOptions.RemoveEmptyEntries);
 7
 8 // Initialize socket pool
 9 SockIOPool pool = SockIOPool.GetInstance ();
10 pool.SetServers (servers);
11 pool.InitConnections = 1;
12 pool.MinConnections = 1;
13 pool.MaxConnections = 3;
14 pool.SocketConnectTimeout = 1000; // socket connection timeout, how many milliseconds the socket will be destroyed after idle
15 pool.SocketTimeout = 3000;
16 pool.MaintenanceSleep = 30; // Maintenance thread rest time
17 pool.Failover = true; // Failover (a backup operation mode)
18 pool.Nagle = false; // whether to use the Nagle algorithm to start the socket
19 pool.Initialize (); // Apply settings and initialize the socket pool
20
21 // Create memcached client
22 client = new MemcachedClient ();
23 client.EnableCompression = false; // Whether to compress
twenty four 
25}
26 public void Set (string key, object value, DateTime exp)
27 {
28 client.Set (key, value, exp);
29}
30
31 public void Set (string key, object value)
32 {
33 client.Set (key, value);
34}
35
36 public object Get (string key)
37 {
38 return client.Get (key);
39}
Copy code
This allows you to add and modify servers through configuration.
 
With the interface class and implementation class, the next step is to implement its factory using Spring.Net.
 
New CacheHelper class, the code is as follows:
Copy code
 1 public class CacheHelper
 2     {
 3 public static ICacheWriter CacheWriter {get; set;}
 4
 5 static CacheHelper ()
 6 {
 7 // If it is a static property, if you want it to have an injected value, you must create an instance before you can inject it
 8 // When the static method is called, the Spring container is not required to create an instance, so the attribute CacheWriter is not injected into the instance
 9 // In the static constructor of the class, force the Spring container to create an instance of a property for us. Because the property is static, you only need to create it once.
10
11 IApplicationContext ctx = ContextRegistry.GetContext ();
12 ctx.GetObject ("CacheHelper");
13
14}
15 public static void WriteCache (string key, object value, DateTime exp)
16 {
17 CacheWriter.Set (key, value, exp);
18}
19 public static void WriteCache (string key, object value)
20 {
21 CacheWriter.Set (key, value);
twenty two         }
twenty three 
24 public static object GetCache (string key)
25 {
26 return CacheWriter.Get (key);
27}
28}
Copy code
public static ICacheWriter CacheWriter {get; set;}
This property is the injection point for Spring.Net.
 
It should be noted that because Spring.Net will only be injected after the class has the first instance, and static methods can only call static fields, static methods and static fields are created when the program starts to run. At this time, there is no first instance of CacheHelper, so the static field CacheWriter is not injected. You need to manually instantiate CacheHelper to let CacheWriter be injected.
 
添加 Add configuration information about CacheHelper and CacheWriter in the Spring node of the configuration file:
 
Copy code
1 <objects xmlns = "http://www.springframework.net">
2 <!-Injection of CacheWriter in CacheHelper, CacheWriter is singleton->
3 <object name = "CacheHelper" type = "MyOA_Common.CacheHelper, MyOA_Common" singleton = "false">
4 <property name = "CacheWriter" ref = "MemcachedWriter" />
5 </ object>
6 <object name = "MemcachedWriter" type = "MyOA_Common.MemcachedWriter, MyOA_Common" singleton = "true">
7
8 </ object>
9 </ objects>
Copy code
If we want to use httpruntime.cache instead of Memcached for cache reads and writes, just modify
 
<object name = "MemcachedWriter" type = "MyOA_Common.MemcachedWriter, MyOA_Common" singleton = "true">
 
Using Spring.Net and interfaces enhances the flexibility of our program.
 
OK, let's test the code on the controller:
Copy code
 1 public class TestController: Controller
 2     {
 3 // GET: / Test /
 4 public ActionResult Test ()
 5 {
 6 CacheHelper.CacheWriter.Set ("test", "Test succeeded");
 7 return View ();
 8         }
 9 
10 [HttpPost]
11 public ActionResult Test (FormCollection form)
12 {
13 string value = (string) CacheHelper.CacheWriter.Get ("test");
14 return Content (value);
15}
16
17}

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.