Memcached與Spring AOP構建數分布式據庫前端緩衝架構,memcachedaop

來源:互聯網
上載者:User

Memcached與Spring AOP構建數分布式據庫前端緩衝架構,memcachedaop

  由於上一篇有介紹了Memcached緩衝,並叢集部署,這邊我們就不介紹,我們直接介紹Memcached與Spring AOP構建分散式資料庫前端緩衝架構

 一.Java 實現Memcached用戶端,實現分布式

(1)需要的jar 

     1)commons-pool-1.5.6.jar

     2)java_memcached-release_2.6.3.jar

     3)slf4j-api-1.6.1.jar

     4)slf4j-simple-1.6.1.jar

(2)Java 實現Memcached用戶端代碼如下:

   

import com.danga.MemCached.MemCachedClient;import com.danga.MemCached.SockIOPool;public class TestCache {/** * @param args */public static void main(String[] args) {       String[] servers = { "192.168.74.129:12000,192.168.74.130:13000"};       SockIOPool pool = SockIOPool.getInstance();       pool.setServers(servers);       pool.setFailover(true);       pool.setInitConn(10);       pool.setMinConn(5);       pool.setMaxConn(250);       pool.setMaintSleep(30);       pool.setNagle(false);       pool.setSocketTO(3000);       pool.setAliveCheck(true);       pool.initialize();       MemCachedClient memCachedClient = new MemCachedClient();       boolean success = memCachedClient.set("zcy", "dataValue");       System.out.println(success);       Object obj= memCachedClient.get("zcy");                System.out.println(obj);}}


二.Memcached與Spring AOP構建資料庫前端緩衝架構,並用Maven來管理項目

(1)我們先溫習一下Spring AOP

   AOP(Aspect Orient Programming)面向切面編程,可以運用在交易管理、安全檢查、緩衝、對象池管理等。面向切面編程中有一個主要的是Advice,這個Advice定義好的切入點處,連接點之前先執行增強中的代碼或者連接點執行後,再執行增強中的代碼等。

(2)我們用Maven管理SpringMVC的jar和Memcached的jar

   我們這裡就介紹Memcached的jar,在POM.XML中添加Memcached對應的jar包

   

 <dependency>  <groupId>com.danga</groupId>  <artifactId>java-memcached</artifactId>  <version>2.6.3</version> </dependency>  <dependency>          <groupId>commons-pool</groupId>          <artifactId>commons-pool</artifactId>          <version>1.5.6</version>      </dependency>   <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-simple</artifactId>          <version>1.6.1</version>      </dependency>      <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-api</artifactId>          <version>1.6.1</version>      </dependency>  


(3)用Spring來管理Memcached串連資訊的配置和實現

     1)global.properties 檔案

#伺服器位址  memcached.server=192.168.74.129:12000memcached.server2=192.168.74.130:13000#初始化時對每個伺服器建立的串連數目  memcached.initConn=20#每個伺服器建立最小的串連數  memcached.minConn=10#每個伺服器建立最大的串連數  memcached.maxConn=50#自查線程周期進行工作,其每次休眠時間  memcached.maintSleep=3000#Socket的參數,如果是true在寫資料時不緩衝,立即發送出去  memcached.nagle=false#Socket阻塞讀取資料的逾時時間  memcached.socketTO=3000memcached.aliveCheck=truememcached.failover=true


2)Spring設定檔(applicationContext-memached.xml)

<!-- 注入屬性檔案 --><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:global.properties</value></list></property></bean>   <bean id="memCachedPool" class="com.danga.MemCached.SockIOPool" factory-method="getInstance" init-method="initialize" destroy-method="shutDown">        <constructor-arg>           <value>memcachedPool</value>         </constructor-arg>                  <property name="servers">             <list>                <value>${memcached.server}</value>                 <value>${memcached.server2}</value>             </list>         </property>        <property name="initConn">            <value>${memcached.initConn}</value>        </property>                <property name="minConn">            <value>${memcached.minConn}</value>        </property>        <property name="maxConn">            <value>${memcached.maxConn}</value>        </property>        <property name="maintSleep">            <value>${memcached.maintSleep}</value>         </property>        <property name="nagle">            <value>${memcached.nagle}</value>        </property>        <property name="socketTO">             <value>${memcached.socketTO}</value>        </property>        <property name="aliveCheck">             <value>${memcached.aliveCheck}</value>        </property>        <property name="failover">             <value>${memcached.failover}</value>        </property>            </bean><bean id="memCachedClient" class="com.danga.MemCached.MemCachedClient">         <constructor-arg>           <span style="color:#ff0000;"><value>memcachedPool</value></span>         </constructor-arg>    </bean>    


3)junit測試一下這樣配置是否正確,代碼如下:

 
  import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.danga.MemCached.MemCachedClient;public class MemcachedServiceTest { private MemCachedClient  memCachedClient; @Before  public void beforeTest(){        ApplicationContext atx = new ClassPathXmlApplicationContext("classpath:applicationContext-memached.xml");        memCachedClient = (MemCachedClient)atx.getBean("memCachedClient");  }@Test public void memCached(){boolean b=memCachedClient.set("hello","dataValue");System.out.println(b);Object obj=memCachedClient.get("hello");System.out.println(obj);}}

  

能儲存並能擷取資料說明配置成功


(4)實現MVC商務邏輯

  
 //Dao層@Service("dataDao")public class DataDaoImpl implements DataDao {@Overridepublic String getData(String name) {return name+" get data";}}      //server層  @Service("dataService")public class DataServiceImpl implements DataService{@Autowiredprivate DataDao dataDao;public String findDataByParams(String name) {return dataDao.getData(name);}}//Controller層@Controllerpublic class IndexController {@Autowiredprivate DataService dataService;@RequestMapping("/index")public String index(Model model,@RequestParam(value="name") String name){String dataValue=dataService.findDataByParams(name);System.out.println(dataValue);return "";}}


(5)Spring AOP與Memcached構建資料庫前端緩衝架構

     1)實現AOP的邏輯代碼

       
@Service("dataInterceptor")public class DataInterceptor  implements MethodInterceptor{@Autowiredprivate MemCachedClient memCachedClient;@Overridepublic Object invoke(MethodInvocation invocation) throws Throwable { Object[] args = invocation.getArguments();      String param=args[0].toString();     Object  object = null;     if(param!=null&&memCachedClient!=null){     object=memCachedClient.get(param);     System.out.println("執行從MemCached擷取的值======="+object);     }     if(object==null){     object =invocation.proceed();     System.out.println("執行資料庫操作擷取的值======="+object);if (object != null) {boolean b=memCachedClient.set(param,object);if(b){ System.out.println("=====儲存值"+object+"到memCached 成功===========");}else{ System.out.println("=====儲存值"+object+"到memCached 失敗===========");}}     System.out.println("沒有從memCached擷取===========");     }else{     System.out.println("從memCached擷取======="+object);     }return object;}}

 2)Spring 設定檔配置AOP

 
  <bean id="dataInterceptorAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"><property name="mappedName"><value>getData</value></property>  <property name="advice" ref="dataInterceptor"/></bean><bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"><property name="beanNames" value="dataDao"/><property name="interceptorNames" value="dataInterceptorAdvisor"/></bean>

配置了對哪個方法進行攔截,這裡我們對getData方法進行攔截



(6)測試Spring AOP與Memcached構建資料庫前端緩衝架構

   

  1)第一次執行我們傳參數hello,Memcached裡面肯定沒有,因為是第一次執行,所示從資料庫擷取對應的值,並儲存到Memcached服務端,:

    

 2)執行第二次,參數是hello,這次沒有去操作資料庫,直接從Memcached服務端擷取對應的值

    

 3)我們這邊對Memcached服務端進行叢集部署,所以我們查看一下,資料儲存到其中的一台,:



三.構建Memcached與Spring AOP構建資料庫前端緩衝架構出現的錯誤

   

 Error:com.schooner.MemCached.SchoonerSockIOPool - attempting to get SockIO from uninitialized pool!


 原因是我們設定MemCachedClient和SockIOPool的ProxName不一樣導致,所以兩個名稱要一樣,:



四.總結

    我們在上一篇介紹了,Memcached叢集部署,有兩台memcached.server=192.168.74.129:12000 和memcached.server2=192.168.74.130:13000,我們通過Memcached用戶端實現了分布式緩衝的,Memcached服務端之間是不能通訊的,所示我們通過Memcached用戶端實現分布式緩衝的。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.