Memcached implements simple business processing

Source: Internet
Author: User

-------- Explanation of the Basic Business Code of memcache

1. Create a memcache client to connect to memcacheconnection

Package COM. boonya. mecache. store; import COM. danga. memcached. memcachedclient; import COM. danga. memcached. sockiopool; public class memcacheconnection {Private Static final memcachedclient = new memcachedclient (); static {string [] servers = {// "192.168.20.10: 11211" "127.0.0.1: 11211 "}; integer [] weights = {3, 3};/* instantiate the connection */sockiopool pool = sockiopool. getinstance (); pool. setservers (servers); pool. setweights (weights);/* set the maximum number of connections in five connection pools, 250 idle time, 6 hours */pool. setinitconn (5); pool. setminconn (5); pool. set maxconn (250); pool. setmaxidle (1000*60*60*24); pool. setmaintsleep (30); pool. setnagle (false); pool. setsocketto (3000); pool. setsocketconnectto (0); pool. initialize (); memcachedclient. setprimitiveasstring (true); memcachedclient. setsanitizekeys (false);} public static memcachedclient getmemcacheclient () {return memcachedclient ;}}

2. memcache cache data operation memstoragehandler

Package COM. boonya. mecache. store; import Java. SQL. connection; import Java. SQL. sqlexception; import Java. SQL. statement; import Java. util. arraylist; import COM. danga. memcached. memcachedclient; public class memstoragehandler {memcachedclient memclient = memcacheconnection. getmemcacheclient (); connection conn = NULL; statement stmt = NULL;/***** perform business processing operations ** @ Param myitems * cache set object */@ suppresswarnings ("raw Types ") Public void doservice (arraylist myitems) {Boolean issaved = This. saveitems (myitems); If (issaved) {This. deletememcacheitem (myitems, memclient, issaved );}} /*** delete data in the memcache cache ** @ Param myitems * @ Param memclient * @ Param issaved */@ suppresswarnings ("rawtypes") Private void deletemcacheitem (arraylist myitems, memcachedclient memclient, Boolean issaved) {If (issaved) {for (INT d = 0; D <myitems. size (); D ++) {memclient. delete (string) myitems. get (D ));}}} /*** batch import of data in memcache cache ** @ Param myitems * Data Set * @ return true/false storage flag */@ suppresswarnings ("rawtypes ") private Boolean saveitems (arraylist myitems) {try {dbconnection dbconn = new dbconnection (); Conn = dbconn. getconnectionbyjdbc ("127.0.0.1", "3306", "lbs", "root", "root"); stmt = Conn. createstatement (); Conn. Setautocommit (false);/* traverse one value from memcached */For (INT h = 0; H <myitems. size (); H ++) {string STR = (string) memclient. get (string) myitems. get (h); string key = (string) myitems. get (h); string keyarr [] = key. split ("_"); string SQL = dbcreatesql. getkey (STR, keyarr [0]); // create an SQL statement stmt.exe cuteupdate (SQL);} Conn. commit ();} catch (exception e) {system. out. println (E. getmessage (); E. printstacktra Ce ();/* if the transaction commit fails, set flag to 1 and roll back */try {Conn. rollback ();} catch (sqlexception E1) {e1.printstacktrace ();} servicelog. logerr (myitems. size (); Return false;} finally {This. free (Conn, stmt);} return true;}/*** release database connection resource usage * @ Param conn * @ Param stmt */private void free (connection Conn, statement stmt) {try {If (stmt! = NULL) {stmt. Close () ;}stmt = NULL;} catch (exception e) {e. printstacktrace () ;}try {If (Conn! = NULL) {conn. setautocommit (true); Conn. Close () ;}conn = NULL ;}catch (exception e) {e. printstacktrace ();}}}

3. Read memdatasearching from memcache cache data

Package COM. boonya. mecache. store; import Java. util. arraylist; import Java. util. iterator; import Java. util. list; import Java. util. map; import COM. danga. memcached. memcachedclient; public class memdatasearching {/*** traverses the memcached method and returns the key arraylist. The actual operation in memcached is stats items-> stats * (this method is not recommended, and traversal is too time-consuming, it is better to define the key-value pairs in the form of key-name, value = MAP/hashmap when the object is stored in memcache in advance, and then remove the values from the map layer by layer, fast) * // @ suppresswa Rnings ({"unchecked", "rawtypes"}) public static arraylist searchdata () {memcachedclient memclient = memcacheconnection. getmemcacheclient (); arraylist keys = new arraylist (30000); map slabs = memclient. statsitems (); iterator itemsitr = slabs. keyset (). iterator (); While (itemsitr. hasnext () {string serverinfo = itemsitr. next (). tostring (); map itemnames = (MAP) slabs. get (serverinfo); iterator item Nameitr = itemnames. keyset (). iterator (); While (itemnameitr. hasnext () {string itemname = itemnameitr. next (). tostring (); string [] itematt = itemname. split (":"); If (itematt [2]. startswith ("Number") {map cacheddump = memclient. statscachedump (integer. parseint (itematt [1]), 0); iterator itr = cacheddump. keyset (). iterator (); While (itr. hasnext () {string serverinfo2 = itr. next (). tostring (); map ite A ms = (MAP) cacheddump. get (serverinfo2); iterator keyitr = items. keyset (). iterator (); While (keyitr. hasnext () {string key = keyitr. next (). tostring (); string memkey = key; keys. add (memkey) ;}}}} return keys ;}/ *** improved reading method, returns the corresponding table object set (key-value pairs are defined in advance when the object is stored in memcache * For example: Key-Name, value = MAP/hashmap and then the values in the next layer of de-map will be fast * structure: partition (multiple), table sharding (multiple), table data rows (multiple rows) ** you can also use the partition/table sharding method) * @ Param tablename: query the name of a data table ** @ Return */@ suppresswarnings ({"rawtypes"}) public static list searchdataplus (string tablename) {memcachedclient memclient = memcacheconnection. getmemcacheclient (); map tableareas = memclient. statsitems (); // obtain the map table set iterator iteratortablearea = tableareas. keyset (). iterator (); While (iteratortablearea. hasnext () {// The reason for using while instead of IF is that there may be multiple table partitions map area = (MAP) iteratortablearea. next (); // obtain the map table if (Area! = NULL) {If (area. containskey (tablename) {// check whether the table map table = (MAP) area to be accessed exists in the partition. get (tablename); If (table! = NULL) {return (list) Table. Values (); // object set in the table }}} return NULL ;}}

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.