springMVC整合jedis-redis-以注解形式使用_第1頁(yè)
springMVC整合jedis-redis-以注解形式使用_第2頁(yè)
springMVC整合jedis-redis-以注解形式使用_第3頁(yè)
springMVC整合jedis-redis-以注解形式使用_第4頁(yè)
springMVC整合jedis-redis-以注解形式使用_第5頁(yè)
已閱讀5頁(yè),還剩16頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、springMVC 整合 jedis+redis ,以注解形式使用前兩天寫過(guò)springMVC+memcachec的整合,我從這個(gè)基礎(chǔ)上改造一下,把redis 和springmvc整合至U起。和memcachecH樣,redis也有java專用的客戶端,官網(wǎng)推薦使用的是:jedis(spring 在jedis 的基礎(chǔ)不如原生態(tài)的jedis好用??戳艘徊糠仲Y料,大家推薦使用 spri ng-data-redis上又包裝了一層),但是實(shí)際中感覺(jué)寫起來(lái)有點(diǎn)麻煩, 所以我利用spring的構(gòu)造注入做了一個(gè)springmvc整合jedis的例子。先了解下redis吧,這些資料袋都是從網(wǎng)上看到的:陽(yáng)Red

2、is使用c語(yǔ)言編寫,面向“鍵/值”對(duì)類型數(shù)據(jù)的分布式NoSql數(shù)據(jù)庫(kù)系統(tǒng)。 目前提供五中數(shù)據(jù)類型stri ng( 字符串)list( 鏈表)Hash( 哈希)set( 集合)zset(sorted set有序集合),有 2 中編碼類型:ziplist,skiplist,當(dāng) zset中數(shù)據(jù)較多時(shí),將會(huì)被重構(gòu)為skiplist 。默認(rèn)端口 6379redis-server.exe :服務(wù)端redis-check-dump.exe:本地?cái)?shù)據(jù)庫(kù)檢查redis-check-aof.exe : 更新日志檢查redis-benchmark.exe :性能測(cè)試,用以模擬同時(shí)由N個(gè)客戶端發(fā)送M個(gè)SETs/GET

3、s 查詢.redis-cli.exe :這個(gè)是客戶端,服務(wù)端開啟后,客戶端就可以輸入各種命令 測(cè)試了先寫一個(gè)Test類,測(cè)一下redis的基本數(shù)據(jù)類型和jedis的一些常用方法。以 下的測(cè)試方法也都是從網(wǎng)上看到的,只不過(guò)為了驗(yàn)證是否準(zhǔn)確以及jar包版本的 問(wèn)題,我自己親自敲了一遍。注意jedis是redis的一個(gè)客戶端,是個(gè)jar包,不要搞混了publicclass Test public static void main(String args) / Jedis js = new Jedis("", 6379);/js.set("key001&

4、quot;, "redis001");/Stri ng val = js.get("key001");/System.out.pri ntln( val);/js.del("key001");測(cè)試Redis的數(shù)據(jù)類型* list*/js.rpush("list1","aaaaaaaaaaaaaaaaaaaaaa");/js.rpush("list1","bbbbbbbbbbbbbbbbbbbbbb");/js.rpush("list1"

5、,"ccccccccccccccccccccc");/js.rpush("list1","dddddddddddddd");/ ListvString> vals = js.lrange("list1", 0, -1);/ for (i nt i = 0; i < vals.size(); i+) /System.out.pri ntln( vals.get(i);/ /* set無(wú)須唯一*/js.sadd("s1","順序3");/js.sadd("s

6、1", "a");/js.sadd("s1", "b");/js.sadd("s1", "1");/js.sadd("s1","蛤蛤蛤");/js.sadd("s1", "2");/js.sadd("s1", "so waht?"/js.sadd("s1", "%A");/js.sadd("s1","

7、;順序1");/js.sadd("s1","亂碼嗎?");/js.sadd("s1","順序2");/ Set<Stri ng> s = js.smembers("s1"); / for (Stri ng stri ng : s) 當(dāng) zset 中數(shù)據(jù)較多時(shí) , 將會(huì)被/ System.out.println(s);/ / js.srem("s1", "蛤蛤蛤 ");/ Hash */Map m = new HashMap();/m.

8、put("1", "t");/m.put("2", "ttt");/ m.put("username", "老王 ");/m.put("password", "123456");/m.put("age", "79");/m.put("sex", "man");/js.hmset("m", m);/List<String> v

9、= js.hmget("m", newString"username","age");/List<String> v1 = js.hmget("m", "sex");/System.out.println(v);/System.out.println(v1);/js.hdel("m", "username");/刪除map中的某一個(gè)鍵的鍵值對(duì)* zset(sorted set 有序集合 )* 有 2 中編碼類型 :ziplist,skiplis

10、t, 重構(gòu)為 skiplist*/js.zadd("zs", 92, "張三 1");/js.zadd("zs", 93, "張三 7");/js.zadd("zs", 94, "張三 5");/js.zadd("zs", 87, "張三 9");/js.zadd("zs", 66, "張三 ");/js.zadd("zs", 19, "張三 0");/Se

11、t<String> sets = js.zrange("zs", 0, -1);/ for (String string : sets) / System.out.println(sets);事務(wù)控制/ * 事務(wù)方式 (Transactions)* 他主要目的是保障, 一個(gè) client 發(fā)起的事務(wù)中的命令可以連續(xù)的執(zhí) 行,而中間不會(huì)插入其他 client 的命令。* 我們調(diào)用 jedis.watch(,) 方法來(lái)監(jiān)控 key ,如果調(diào)用后 key 值發(fā)生 變化,則整個(gè)事務(wù)會(huì)執(zhí)行失敗。* 另外,事務(wù)中某個(gè)操作失敗,并不會(huì)回滾其他操作。這一點(diǎn)需要注、八 意。* 還

12、有,我們可以使用 discard() 方法來(lái)取消事務(wù)。*/ Jedis js1 = new Jedis("", 6379);/long s = System.currentTimeMillis();/Transaction tx = js1.multi();/for (int i = 0; i < 99999; i+) / tx.set("keyttt"+i, "valttt"+i);/List<Object> res= tx.exec();/long e = System.currentTimeM

13、illis();/System.out.println(e-s)/1000.0+"秒 ");/System.out.println(res);/js1.disconnect();*/*/這樣可以取得非常好的執(zhí)行效率。這就是管道 */ / Jedis js2 = new Jedis("", 6379);/long s = System.currentTimeMillis();/Pipeline pe = js2.pipelined();/ for (int i = 0; i < 9999; i+) / pe.set("ke

14、ya"+i, "valuea"+i);/List<Object> l = pe.syncAndReturnAll();/long e = System.currentTimeMillis();/System.out.println(e-s)/1000.0+"秒");/js2.disconnect();返回結(jié)果*管道(Pipeli ning) 有時(shí),我們需要采用異步方式,一次發(fā)送多個(gè)指令,不同步等待其/*/*管道中調(diào)用事務(wù)/* 管道中調(diào)用事務(wù)* 在用法上看,管道中包含了事務(wù)*/ / Jedis js3 = new Jedis(&quo

15、t;", 6379);/ long s = System.currentTimeMillis();/ Pipeline pe = js3.pipelined();/ pe.multi();/for (int i = 0; i < 9999; i+) / pe.set("keybb"+i, "valuebb"+i);/ / pe.exec();/List<Object> l = pe.syncAndReturnAll();/long e = System.currentTimeMillis();/ System

16、.out.println(e-s)/1000.0+"秒 ");/ js3.disconnect();/* *分布式直連同步調(diào)用分布式直連同步調(diào)用線程不安全的,不建議在線程池中使用直連*/List<JedisShardInfo> shards = Arrays.asList( new JedisShardInfo("localhost",6379), new JedisShardInfo("localhost",6380);ShardedJedis sharding = new ShardedJedis(shards); l

17、ong start = System.currentTimeMillis();for (int i = 0; i < 100000; i+) String result = sharding.set("sn" + i, "n" + i);long end = System.currentTimeMillis();System.out.println("SimpleSharing SET: " + (end - start)/1000.0) + " seconds");/ sharding.disconnect

18、();分布式直連同步調(diào)用/new JedisShardInfo("localhost",6379),/new JedisShardInfo("localhost",6380);/ShardedJedis sharding = new ShardedJedis(shards);/ShardedJedisPipeline pipeline = sharding.pipelined();/long start = System.currentTimeMillis();/for (int i = 0; i < 100000; i+) / pipeline.

19、set("sp" + i, "p" + i);/List<Object> results = pipeline.syncAndReturnAll();/long end = System.currentTimeMillis();/System.out.println("PipelinedSharing SET: " + (end -start)/1000.0) + " seconds");/ sharding.disconnect();分布式連接池同步調(diào)用* 同步方式*/ List<JedisSh

20、ardInfo> shards = Arrays.asList(/new JedisShardInfo("localhost",6379),/new JedisShardInfo("localhost",6380);/ ShardedJedisPool pool = new ShardedJedisPool(newJedisPoolConfig(), shards);/ ShardedJedis one = pool.getResource();/long start = System.currentTimeMillis();/for (int i

21、 = 0; i < 100000; i+) /String result = one.set("spn" + i, "n" + i);/long end = System.currentTimeMillis();/pool.returnResource(one);/System.out.println("SimplePool SET: " + (end -start)/1000.0) + " seconds");/ / pool.destroy();/分布式連接池異步調(diào)用*'* 異步方式*/Listv

22、JedisShard lnfo> shards = Arrays.asList(/new JedisShardl nfo("localhost",6379),/new JedisShardI nfo("localhost",6380);/ShardedJedisPool pool = new ShardedJedisPool( newJedisPoolC on fig(), shards);/ ShardedJedis one = pool.getResource();/ / ShardedJedisPipeli ne pipeli ne = on

23、 e.pipeli ned();/ long start = System.curre ntTimeMillis();/for (int i = 0; i < 100000; i+) /pipeli ne.set("spp n" + i, " n" + i);/List<Object> results = pipeli ne.s yncAn dReturnAll();/long end = System.curre ntTimeMillis();/pool.returnResource(o ne);/System.out.pri ntl

24、 n( "Pipeli nedPool SET: " + (end -start)/1000.0) + " sec on ds");/ pool.destroy();其他/*清空所有*/js.flushAll();*銷毀鏈接*/js.disc onn ect();開始貼代碼了,springMVC整合jedisweb.xml0v?xml versio n="1.0" en codi ng="UTF-8"?>vweb-app xml ns:xsi="/2001/XMLSc

25、hema-i nsta nee"xml ns="http:/java.s un .com/xml/ns/javaee"xsi:schemaLocatio n="http:/java.s un .com/xml/ns/javaeehttp:/java.s un .com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" versio n="2.5">vdisplay-name>Spri ngMVC-Redisv/display-name><!

26、- 弓 I入 spri ng -><liste ner><listener- class >org.springframework.web.context.ContextLoaderListener </listener- class ></liste ner><con text-param>vparam-n ame>c on textC on figLocati on</param-n ame> <param-value>classpath*:/applicati onCon text*.xml&

27、lt;/param-value> v/con text-param><!-引入 sprin gMVC -><servlet>vservlet -n ame>spri ngMVCv/servlet -n ame>vservlet- class >org.springframework.web.servlet.DispatcherServlet</ser vlet- class ><ini t-param>vparam-n ame>c on textC on figLocati on</param-n ame

28、><param-value>classpath*:/spri ng-servlet-c on fig.xmlv/param-value>v/ini t-param>v/servlet>vservlet-mapp ing>vservlet -n ame>spri ngMVCv/servlet -n ame> vurl-pattern>/v/url-pattern>v/servlet-mapp ing>v!-編碼 UTF-8 ->vfilter>vfilter- name>Spri ngMVC-Redis-E

29、 ncodi ngv/filter- name>vfilter-class >org.springframework.web.filter.CharacterEncodingFilterv/filter-class >vini t-param>vparam-n ame>e ncod in gv/param-n ame><param-value>UTF-8</param-value>v/ini t-param><ini t-param>vparam-n ame>forceE ncod in gv/param-n

30、ame><param-value> true v/param-value>v/ini t-param>v/filter>vfilter-mapp ing>vfilter- name>Spri ngMVC-Redis-E ncodi ngv/filter- name>vurl-patter n>/*v/url-pattern>v/filter-mapp ing>v/web-app>in dex.jsp3v% page Ian guage="java" con te ntType="text

31、/html; charset=utf-8" pageE ncodi ng="utf-8"%>v!DOCTYPE html PUBLIC "-/W3C/DTD HTML 4.01 Tran siti on al/EN" "/TR/html4/loose.dtd">vhtml>vhead>vscript type="text/javascript"src="$pageC on text.request.c on textPath /js/jqu

32、ery/jquery-1.8.0. min.j s"x/script>vmeta http-equiv="C onten t-Type" con te nt="text/html; charset=utf-8"> vtitle>i ndex 2v/title>v/head>vbody>vdivxfont color="red" size="10px">$returnMsgv/font>v/div>vformaction="$pageC on

33、text.request.c on textPath /TestRequest/test" method="post" n ame="logi nFo rm" id="log inForm">vdiv>用戶名:<input class ="username" type="text" id="username"n ame="user name" value=”/>v/div><div >密碼:<inp

34、ut class ="password" type="password" id="password" n ame="password" value=""/></div><div> <in put type="butt on" value="submit" on click="log in()"/></div></form><script type="tex

35、t/javascript">fun ctio n logi n()var user name = $("#username").val();var password = $("#password").val();$("#logi nForm").submit();docume nt.on keydow n=fun ctio n(eve nt)e = eve nt ? eve nt :(w in dow.eve nt ? win dow.eve nt :n ull );if (e.keyCode=13)logi n();

36、</script></body></html>spri ng-servlet-c on fig.xmln<?xml versio n="1.0" en codi ng="UTF-8"?><bea ns xml ns="/schema/bea ns"xml ns:mvc="/schema/mvc"xml ns:c on text="http

37、://schema/co ntext"xml ns:xsi="/2001/XMLSchema-i nsta nee"xsi:schemaLocatio n="/schema/bea ns/schema/bea ns/spri ng-bea ns-3.1.xsd/schema/c on texthttp: /

38、/schema/context/spring-context-3.1.xsdhttp: //schema/mvchttp: //schema/mvc/spring-mvc-3.1.xsd"><!-使用 Controllers 前配置 -><mvc:annotation-driven /><!-容器加載時(shí) 自動(dòng)掃描所有注解 -><context:component-scan base- package=

39、"com.test"use- default -filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /><context:include-filter type="annotation" expression="org.springframework.stereotype.Service&q

40、uot; /><context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /><context:include-filter type="annotation" expression="org.springframework.stereotype.Component" /></context:component-scan><!-配置靜態(tài)

41、資源 -><mvc:resources mapping="/js/*" location="/js/" /><mvc:resources mapping="/image/*" location="/image/" /><mvc:resources mapping="/css/*" location="/css/" /><!-使用 jsp 作為視圖 -><beanclass ="org.springframe

42、work.web.servlet.view.InternalResourceViewResol ver"><property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value> </property><!-目標(biāo)路徑返回到 pages 下 使用 jsp 作為視圖 -><property name="prefix" value="/pages/">&

43、lt;/property><property name="suffix" value=".jsp"></property></bean><!-異常處理 -><beanclass ="org.springframework.web.servlet.handler.SimpleMappingException Resolver"><property name="exceptionMappings">vprops>vpropkey=&qu

44、ot;org.apache.shiro.authz.U nauthorizedExcepti on" >error/403</prop></props></property>v/bea n>v/bea ns>先把這些貼上來(lái)是因?yàn)檫@些文件內(nèi)容都和上篇博文” springMVC+memcached “的一模一樣applicatio nCon text.xml利用spri ng的構(gòu)造注入,把集群參數(shù)傳入 Redis In itBea n中,并且在項(xiàng)目啟動(dòng)的時(shí)候加載Redis In itBea n 的有參構(gòu)造方法0<?xml ver

45、sio n="1.0" en codi ng="UTF-8"?><bea ns xml ns="/schema/bea ns"xml ns:xsi="/2001/XMLSchema-i nsta nee"xml ns:co ntext="/schema/co ntext"xml ns:aop="http:/www.springf

46、/schema/aop"xml ns:tx="/schema/tx"xsi:schemaLocatio n="/schema/bea ns/schema/bea ns/spri ng-bea ns-3.1.xsd/schema/c on texthttp: /www.springframework.or

47、g/schema/context/spring-context-3.1.xsd/schema/aop/schema/aop/spri ng-aop-3.1.xsd/schema/tx/schema/tx/spri ng-tx-3.1.xsd"><bea n id="Redis In itBea n"class ="

48、com.test.test.Redis In itBea n" ><!- IP:Port -><con structor-arg in dex="0" type="List"><list><value>:6379</value><value>7:6380</value> v/list>v/con structor-arg><!- maxWaitMillis -><con structor

49、-arg in dex="1" type="l on g"> <value>1000</value>v/con structor-arg><!- MaxIdle -><con structor-arg in dex="2" type二"i nt"> <value>200</value>v/con structor-arg><!- test On Borrow -><con structor-arg in de

50、x="3" type="Boolea n"> <value> true </value>v/con structor-arg>v/bea n>v/bea ns>Redis In itBea n.java這里面要說(shuō)一下,使用的是分布式連接池 異步調(diào)用!0嚼package com.test.test;import java.util.Arrays;import java.util.List;import redis.clients.jedis.JedisPoolConfig;import redis.clien

51、ts.jedis.JedisShardInfo;import redis.clients.jedis.ShardedJedis;import redis.clients.jedis.ShardedJedisPool;public class Redis In itBea n private List Host;private long maxWaitMillis;private int MaxIdle;private Boolea n test On Borrow;private static ListvJedisShard lnfo> shards ;private static Sh

52、ardedJedisPool pool;private static ShardedJedis jedis;public RedisInitBean(List host, long maxWaitMillis, int maxIdle, Boolea n test On Borrow) super ();Host = host;this .maxWaitMillis = maxWaitMillis;MaxIdle = maxIdle;this .test On Borrow = test On Borrow;if (host.size()!=0)for (int i = 0; i < h

53、ost.size(); i+) Stri ng h = (Stri ng) host.get(i).split(":");shards = Arrays.asList(newJedisShardI nfo(h0.trim(),l nteger.parse In t(h1.trim();System.out.pri ntln( shards); else System.out.println(”請(qǐng)檢查Redis配置,host項(xiàng)為必填項(xiàng)!格式IP:PORT");pool =newShardedJedisPool( newJedisPoolConfig(), shard

54、s);jedis = pool.getResource();public synchronized ShardedJedis getSingletonlnstance() return jedis;public synchroni zed static void returnResource()pool.retur nResource(jedis);public synchronized static void destroy()pool.destroy();TestRequest.java剛才我們寫的index.jsp中,提交了表單后瀏覽器會(huì)發(fā)起請(qǐng)求,spring攔截請(qǐng) 求后會(huì)找到注解匹配的

55、類中的方法,TestRequest就是了。0package com.test.web;import java.util.List;import javax.servlet.http.HttpSession;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframewo

56、rk.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;import redis.clients.jedis.ShardedJedis;import redis.clients.jedis.ShardedJedisPipeline;import com.test.test.RedisInitBean;Co ntrollerRequestM appi ng("/TestRequest") public class TestRequest Autowiredp

57、rivate RedisInitBean rib;Request Map pi ng("/test")public ModelAndView test(RequestParam(value = "username")finalString userid,RequestParam(value = "password")final Stri ng passwd,HttpSessi on sessi on)ModelA ndView m =newModelA ndView();m.setViewName("./i ndex&quo

58、t;);ShardedJedis jedis = rib.getS in glet onln sta nce(); ShardedJedisPipeli ne pipeli ne = jedis.pipeli ned(); long start = System.curre ntTimeMillis();for ( int i = 0; i < 99999; i+) pipeli ne.set("zhe nbn" + i, " n" + i);List<Object> results = pipeline.syncAndReturnAl

59、l();long end = System.curre ntTimeMillis(); rib.returnResource();rib.destroy();System.out.println(”分布式連接池異步調(diào)用耗時(shí):"+ (end -start)/1OOO.O) + " 秒");try Thread.sleep(5000);/睡5秒,然后打印jedis返回的結(jié)果 catch (In terruptedExcepti on e) e.pri ntStackTrace();System.out.pri ntl n(”返回結(jié)果:"+results);m.addObject("returnMsg","么么噠!");return m;存完之后,我們可以取一下試試,看看

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論