springmvc整合redis架构搭建实例
1 原文 http://www.cnblogs.com/dennisit/p/3614521.html 2 3 新换环境,又有新东西可以学习了,哈皮! 抽空学习之余看了一下redis,个人对Springmvc的爱是忠贞不渝,所以整理了一下Springmvc整合redis的环境搭建.分享学习. 4 5 第一步 : 创建 maven 项目 : 6 7 实例pom.xml内容如下 8 9 <?xml version="1.0" encoding="UTF-8"?> 10 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 11 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 12 13 <modelVersion>4.0.0</modelVersion> 14 <packaging>war</packaging> 15 16 <name>orm-bae</name> 17 <groupId>com.orm</groupId> 18 <artifactId>orm-bae</artifactId> 19 <version>0.0.1-SNAPSHOT</version> 20 21 <properties> 22 <org.springframework.version>3.0.5.RELEASE</org.springframework.version> 23 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 24 </properties> 25 26 <dependencies> 27 28 <!-- config junit jar --> 29 <dependency> 30 <groupId>junit</groupId> 31 <artifactId>junit</artifactId> 32 <version>4.8.2</version> 33 <scope>test</scope> 34 </dependency> 35 36 <!-- config redis data and client jar--> 37 <dependency> 38 <groupId>org.springframework.data</groupId> 39 <artifactId>spring-data-redis</artifactId> 40 <version>1.0.2.RELEASE</version> 41 </dependency> 42 <dependency> 43 <groupId>redis.clients</groupId> 44 <artifactId>jedis</artifactId> 45 <version>2.1.0</version> 46 </dependency> 47 48 <!-- config need jar --> 49 <dependency> 50 <groupId>commons-lang</groupId> 51 <artifactId>commons-lang</artifactId> 52 <version>2.6</version> 53 </dependency> 54 55 <dependency> 56 <groupId>org.apache.geronimo.specs</groupId> 57 <artifactId>geronimo-servlet_3.0_spec</artifactId> 58 <version>1.0</version> 59 </dependency> 60 61 <!-- cofig spring jar --> 62 <dependency> 63 <groupId>org.springframework</groupId> 64 <artifactId>spring-core</artifactId> 65 <version>${org.springframework.version}</version> 66 </dependency> 67 68 <dependency> 69 <groupId>org.springframework</groupId> 70 <artifactId>spring-expression</artifactId> 71 <version>${org.springframework.version}</version> 72 </dependency> 73 74 <dependency> 75 <groupId>org.springframework</groupId> 76 <artifactId>spring-beans</artifactId> 77 <version>${org.springframework.version}</version> 78 </dependency> 79 80 <dependency> 81 <groupId>org.springframework</groupId> 82 <artifactId>spring-aop</artifactId> 83 <version>${org.springframework.version}</version> 84 </dependency> 85 86 <dependency> 87 <groupId>org.springframework</groupId> 88 <artifactId>spring-context</artifactId> 89 <version>${org.springframework.version}</version> 90 </dependency> 91 92 <dependency> 93 <groupId>org.springframework</groupId> 94 <artifactId>spring-context-support</artifactId> 95 <version>${org.springframework.version}</version> 96 </dependency> 97 98 <dependency> 99 <groupId>org.springframework</groupId> 100 <artifactId>spring-tx</artifactId> 101 <version>${org.springframework.version}</version> 102 </dependency> 103 104 <dependency> 105 <groupId>org.springframework</groupId> 106 <artifactId>spring-jdbc</artifactId> 107 <version>${org.springframework.version}</version> 108 </dependency> 109 110 <dependency> 111 <groupId>org.springframework</groupId> 112 <artifactId>spring-orm</artifactId> 113 <version>${org.springframework.version}</version> 114 </dependency> 115 116 <dependency> 117 <groupId>org.springframework</groupId> 118 <artifactId>spring-oxm</artifactId> 119 <version>${org.springframework.version}</version> 120 </dependency> 121 122 <dependency> 123 <groupId>org.springframework</groupId> 124 <artifactId>spring-web</artifactId> 125 <version>${org.springframework.version}</version> 126 </dependency> 127 128 <dependency> 129 <groupId>org.springframework</groupId> 130 <artifactId>spring-webmvc</artifactId> 131 <version>${org.springframework.version}</version> 132 </dependency> 133 134 <dependency> 135 <groupId>org.springframework</groupId> 136 <artifactId>spring-webmvc-portlet</artifactId> 137 <version>${org.springframework.version}</version> 138 </dependency> 139 140 <dependency> 141 <groupId>org.springframework</groupId> 142 <artifactId>spring-test</artifactId> 143 <version>${org.springframework.version}</version> 144 <scope>test</scope> 145 </dependency> 146 147 </dependencies> 148 149 <build> 150 <resources> 151 <resource> 152 <directory>/src/main/resources</directory> 153 <filtering>true</filtering> 154 </resource> 155 </resources> 156 </build> 157 </project> 158 第二步 : 配置文件整合 159 160 Web.xml文件配置 161 162 <?xml version="1.0" encoding="UTF-8"?> 163 <web-app version="2.4" 164 xmlns="http://java.sun.com/xml/ns/j2ee" 165 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 166 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 167 168 <listener> 169 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 170 </listener> 171 172 <context-param> 173 <param-name>contextConfigLocation</param-name> 174 <param-value>/WEB-INF/context/spring-context.xml</param-value> 175 </context-param> 176 177 <!-- Spring字符集过滤器 --> 178 <filter> 179 <filter-name>SpringEncodingFilter</filter-name> 180 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 181 <init-param> 182 <param-name>encoding</param-name> 183 <param-value>UTF-8</param-value> 184 </init-param> 185 <init-param> 186 <param-name>forceEncoding</param-name> 187 <param-value>true</param-value> 188 </init-param> 189 </filter> 190 <filter-mapping> 191 <filter-name>SpringEncodingFilter</filter-name> 192 <url-pattern>/*</url-pattern> 193 </filter-mapping> 194 195 196 <servlet> 197 <servlet-name>mvc</servlet-name> 198 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 199 <init-param> 200 <param-name>contextConfigLocation</param-name> 201 <param-value>/WEB-INF/context/spring-mvc.xml</param-value> 202 </init-param> 203 <load-on-startup>2</load-on-startup> 204 </servlet> 205 206 <servlet-mapping> 207 <servlet-name>mvc</servlet-name> 208 <url-pattern>/</url-pattern> 209 </servlet-mapping> 210 211 <welcome-file-list> 212 <welcome-file>index.jsp</welcome-file> 213 </welcome-file-list> 214 215 </web-app> 216 spring-context.xml内容 217 218 <?xml version="1.0" encoding="UTF-8"?> 219 <beans xmlns="http://www.springframework.org/schema/beans" 220 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 221 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 222 xmlns:util="http://www.springframework.org/schema/util" 223 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 224 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 225 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 226 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> 227 228 229 <!-- 激活@Controller模式 --> 230 <mvc:annotation-driven /> 231 232 <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 需要更改 --> 233 <context:component-scan base-package="com.pudp.bae.*" /> 234 235 <!-- 引入同文件夹下的redis属性配置文件 --> 236 <import resource="redis-context.xml"/> 237 238 </beans> 239 redis-context.xml内容 240 241 <beans xmlns="http://www.springframework.org/schema/beans" 242 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 243 xmlns:p="http://www.springframework.org/schema/p" 244 xmlns:tx="http://www.springframework.org/schema/tx" 245 xmlns:context="http://www.springframework.org/schema/context" 246 xsi:schemaLocation=" 247 http://www.springframework.org/schema/beans 248 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 249 http://www.springframework.org/schema/tx 250 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 251 http://www.springframework.org/schema/context 252 http://www.springframework.org/schema/context/spring-context-3.0.xsd 253 "> 254 255 <!-- scanner redis properties --> 256 <context:property-placeholder location="/WEB-INF/property/redis.properties" /> 257 258 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 259 <property name="maxIdle" value="${redis.maxIdle}" /> 260 <property name="maxActive" value="${redis.maxActive}" /> 261 <property name="maxWait" value="${redis.maxWait}" /> 262 <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 263 </bean> 264 265 <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 266 p:host-name="${redis.host}" 267 p:port="${redis.port}" 268 p:password="${redis.pass}" 269 p:pool-config-ref="poolConfig"/> 270 271 <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> 272 <property name="connectionFactory" ref="connectionFactory" /> 273 </bean> 274 275 </beans> 276 Redis.properties文件内容 277 278 # Redis settings 279 #redis.host=192.168.20.101 280 #redis.port=6380 281 #redis.pass=foobared 282 redis.host=127.0.0.1 283 redis.port=6379 284 redis.pass= 285 286 redis.maxIdle=300 287 redis.maxActive=600 288 redis.maxWait=1000 289 redis.testOnBorrow=true 290 第三步 :Springmvc 对 Redis 的支持与实例应用 . 291 292 实例对象 293 294 295 package com.pudp.bae.model; 296 297 import com.pudp.bae.base.BaseModel; 298 299 public class Member extends BaseModel{ 300 301 /** 302 * 303 */ 304 private static final long serialVersionUID = -1959528436584592183L; 305 306 307 private String id; 308 private String nickname; 309 310 public Member(){} 311 312 public Member(String id, String nickname){ 313 this.setId(id); 314 this.setNickname(nickname); 315 } 316 317 public String getId() { 318 return id; 319 } 320 public void setId(String id) { 321 this.id = id; 322 } 323 public String getNickname() { 324 return nickname; 325 } 326 public void setNickname(String nickname) { 327 this.nickname = nickname; 328 } 329 330 } 331 View Code 332 Redis对象持久化操作 333 334 package com.pudp.bae.base; 335 336 import java.io.Serializable; 337 338 import org.springframework.beans.factory.annotation.Autowired; 339 import org.springframework.data.redis.core.RedisTemplate; 340 import org.springframework.data.redis.serializer.RedisSerializer; 341 342 public abstract class RedisGeneratorDao<K extends Serializable, V extends Serializable> { 343 344 @Autowired 345 protected RedisTemplate<K,V> redisTemplate ; 346 347 /** 348 * 设置redisTemplate 349 * @param redisTemplate the redisTemplate to set 350 */ 351 public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) { 352 this.redisTemplate = redisTemplate; 353 } 354 355 /** 356 * 获取 RedisSerializer 357 * <br>------------------------------<br> 358 */ 359 protected RedisSerializer<String> getRedisSerializer() { 360 return redisTemplate.getStringSerializer(); 361 } 362 363 } 364 package com.pudp.bae.base; 365 366 import java.io.Serializable; 367 368 import org.springframework.beans.factory.annotation.Autowired; 369 import org.springframework.data.redis.core.RedisTemplate; 370 import org.springframework.data.redis.serializer.RedisSerializer; 371 372 public abstract class RedisGeneratorDao<K extends Serializable, V extends Serializable> { 373 374 @Autowired 375 protected RedisTemplate<K,V> redisTemplate ; 376 377 /** 378 * 设置redisTemplate 379 * @param redisTemplate the redisTemplate to set 380 */ 381 public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) { 382 this.redisTemplate = redisTemplate; 383 } 384 385 /** 386 * 获取 RedisSerializer 387 * <br>------------------------------<br> 388 */ 389 protected RedisSerializer<String> getRedisSerializer() { 390 return redisTemplate.getStringSerializer(); 391 } 392 393 } 394 redis对象操作 395 396 package com.pudp.bae.dao.redis; 397 398 import java.util.ArrayList; 399 import java.util.List; 400 401 import org.springframework.dao.DataAccessException; 402 import org.springframework.data.redis.connection.RedisConnection; 403 import org.springframework.data.redis.core.RedisCallback; 404 import org.springframework.data.redis.serializer.RedisSerializer; 405 import org.springframework.stereotype.Repository; 406 import org.springframework.util.Assert; 407 408 import com.pudp.bae.base.RedisGeneratorDao; 409 import com.pudp.bae.model.Member; 410 411 412 /** 413 * 参看博客 <br> 414 * ------------------------------------------------------------------------------- 415 * http://blog.csdn.net/java2000_wl/article/details/8543203 416 * ------------------------------------------------------------------------------- 417 */ 418 419 @Repository(value="memberDao") 420 public class MemberDaoImpl extends RedisGeneratorDao<String,Member> implements MemberDao{ 421 422 423 /** 424 * 添加对象 425 */ 426 @Override 427 public boolean add(final Member member) { 428 boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { 429 public Boolean doInRedis(RedisConnection connection) 430 throws DataAccessException { 431 RedisSerializer<String> serializer = getRedisSerializer(); 432 byte[] key = serializer.serialize(member.getId()); 433 byte[] name = serializer.serialize(member.getNickname()); 434 return connection.setNX(key, name); 435 } 436 }); 437 return result; 438 } 439 440 /** 441 * 添加集合 442 */ 443 @Override 444 public boolean add(final List<Member> list) { 445 Assert.notEmpty(list); 446 boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { 447 public Boolean doInRedis(RedisConnection connection) 448 throws DataAccessException { 449 RedisSerializer<String> serializer = getRedisSerializer(); 450 for (Member member : list) { 451 byte[] key = serializer.serialize(member.getId()); 452 byte[] name = serializer.serialize(member.getNickname()); 453 connection.setNX(key, name); 454 } 455 return true; 456 } 457 }, false, true); 458 return result; 459 } 460 461 /** 462 * 删除对象 ,依赖key 463 */ 464 public void delete(String key) { 465 List<String> list = new ArrayList<String>(); 466 list.add(key); 467 delete(list); 468 } 469 470 /** 471 * 删除集合 ,依赖key集合 472 */ 473 public void delete(List<String> keys) { 474 redisTemplate.delete(keys); 475 } 476 477 /** 478 * 修改对象 479 */ 480 public boolean update(final Member member) { 481 String key = member.getId(); 482 if (get(key) == null) { 483 throw new NullPointerException("数据行不存在, key = " + key); 484 } 485 boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { 486 public Boolean doInRedis(RedisConnection connection) 487 throws DataAccessException { 488 RedisSerializer<String> serializer = getRedisSerializer(); 489 byte[] key = serializer.serialize(member.getId()); 490 byte[] name = serializer.serialize(member.getNickname()); 491 connection.set(key, name); 492 return true; 493 } 494 }); 495 return result; 496 } 497 498 /** 499 * 根据key获取对象 500 */ 501 public Member get(final String keyId) { 502 Member result = redisTemplate.execute(new RedisCallback<Member>() { 503 public Member doInRedis(RedisConnection connection) 504 throws DataAccessException { 505 RedisSerializer<String> serializer = getRedisSerializer(); 506 byte[] key = serializer.serialize(keyId); 507 byte[] value = connection.get(key); 508 if (value == null) { 509 return null; 510 } 511 String nickname = serializer.deserialize(value); 512 return new Member(keyId, nickname); 513 } 514 }); 515 return result; 516 } 517 518 } 519 package com.pudp.bae.dao.redis; 520 521 import java.util.ArrayList; 522 import java.util.List; 523 524 import org.springframework.dao.DataAccessException; 525 import org.springframework.data.redis.connection.RedisConnection; 526 import org.springframework.data.redis.core.RedisCallback; 527 import org.springframework.data.redis.serializer.RedisSerializer; 528 import org.springframework.stereotype.Repository; 529 import org.springframework.util.Assert; 530 531 import com.pudp.bae.base.RedisGeneratorDao; 532 import com.pudp.bae.model.Member; 533 534 535 /** 536 * 参看博客 <br> 537 * ------------------------------------------------------------------------------- 538 * http://blog.csdn.net/java2000_wl/article/details/8543203 539 * ------------------------------------------------------------------------------- 540 */ 541 542 @Repository(value="memberDao") 543 public class MemberDaoImpl extends RedisGeneratorDao<String,Member> implements MemberDao{ 544 545 546 /** 547 * 添加对象 548 */ 549 @Override 550 public boolean add(final Member member) { 551 boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { 552 public Boolean doInRedis(RedisConnection connection) 553 throws DataAccessException { 554 RedisSerializer<String> serializer = getRedisSerializer(); 555 byte[] key = serializer.serialize(member.getId()); 556 byte[] name = serializer.serialize(member.getNickname()); 557 return connection.setNX(key, name); 558 } 559 }); 560 return result; 561 } 562 563 /** 564 * 添加集合 565 */ 566 @Override 567 public boolean add(final List<Member> list) { 568 Assert.notEmpty(list); 569 boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { 570 public Boolean doInRedis(RedisConnection connection) 571 throws DataAccessException { 572 RedisSerializer<String> serializer = getRedisSerializer(); 573 for (Member member : list) { 574 byte[] key = serializer.serialize(member.getId()); 575 byte[] name = serializer.serialize(member.getNickname()); 576 connection.setNX(key, name); 577 } 578 return true; 579 } 580 }, false, true); 581 return result; 582 } 583 584 /** 585 * 删除对象 ,依赖key 586 */ 587 public void delete(String key) { 588 List<String> list = new ArrayList<String>(); 589 list.add(key); 590 delete(list); 591 } 592 593 /** 594 * 删除集合 ,依赖key集合 595 */ 596 public void delete(List<String> keys) { 597 redisTemplate.delete(keys); 598 } 599 600 /** 601 * 修改对象 602 */ 603 public boolean update(final Member member) { 604 String key = member.getId(); 605 if (get(key) == null) { 606 throw new NullPointerException("数据行不存在, key = " + key); 607 } 608 boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { 609 public Boolean doInRedis(RedisConnection connection) 610 throws DataAccessException { 611 RedisSerializer<String> serializer = getRedisSerializer(); 612 byte[] key = serializer.serialize(member.getId()); 613 byte[] name = serializer.serialize(member.getNickname()); 614 connection.set(key, name); 615 return true; 616 } 617 }); 618 return result; 619 } 620 621 /** 622 * 根据key获取对象 623 */ 624 public Member get(final String keyId) { 625 Member result = redisTemplate.execute(new RedisCallback<Member>() { 626 public Member doInRedis(RedisConnection connection) 627 throws DataAccessException { 628 RedisSerializer<String> serializer = getRedisSerializer(); 629 byte[] key = serializer.serialize(keyId); 630 byte[] value = connection.get(key); 631 if (value == null) { 632 return null; 633 } 634 String nickname = serializer.deserialize(value); 635 return new Member(keyId, nickname); 636 } 637 }); 638 return result; 639 } 640 641 } 642 Controller实现 643 644 package com.pudp.bae.controller; 645 646 import java.util.HashMap; 647 import java.util.Map; 648 649 import javax.annotation.Resource; 650 import javax.servlet.http.HttpServletRequest; 651 import javax.servlet.http.HttpServletResponse; 652 653 import org.springframework.stereotype.Controller; 654 import org.springframework.web.bind.annotation.ModelAttribute; 655 import org.springframework.web.bind.annotation.PathVariable; 656 import org.springframework.web.bind.annotation.RequestMapping; 657 import org.springframework.web.bind.annotation.RequestMethod; 658 import org.springframework.web.servlet.ModelAndView; 659 660 import com.pudp.bae.base.BaseMultiController; 661 import com.pudp.bae.model.Member; 662 import com.pudp.bae.service.MemberService; 663 664 @Controller 665 @RequestMapping(value="/member") 666 public class MemberController extends BaseMultiController{ 667 668 @Resource(name="memberService") 669 private MemberService memberService; 670 671 public void setMemberService(MemberService memberService) { 672 this.memberService = memberService; 673 } 674 675 @RequestMapping(value={"/add","/add.html"},method={RequestMethod.GET}) 676 public ModelAndView add(HttpServletRequest request,HttpServletResponse response){ 677 Map<String,Object> map = new HashMap<String, Object>(); 678 return toView("member/add", map); 679 } 680 681 @RequestMapping(value={"/add","/add.html"},method={RequestMethod.POST}) 682 public ModelAndView addMember(HttpServletRequest request,HttpServletResponse response, 683 @ModelAttribute("member")Member member){ 684 Map<String,Object> map = new HashMap<String, Object>(); 685 System.out.println(member); 686 map.put("message", "成功添加数据到库," + member); 687 this.memberService.add(member); 688 return toView("member/message", map); 689 } 690 691 @RequestMapping(value={"/{id:\\d+}/query","/{id:\\d+}/query.html"},method={RequestMethod.GET,RequestMethod.POST}) 692 public ModelAndView queryMember(HttpServletRequest request,HttpServletResponse response, 693 @PathVariable("id")String id){ 694 Map<String,Object> map = new HashMap<String, Object>(); 695 System.out.println(id); 696 Member member = this.memberService.get(id); 697 if(null!=member){ 698 map.put("message", "查询Id=" + id + "的用户名为:" + member.getNickname()); 699 }else{ 700 map.put("message", "没有查询到与Id=" + id + "相关的数据"); 701 } 702 return toView("member/message", map); 703 } 704 705 @RequestMapping(value={"/{id:\\d+}/delete","/{id:\\d+}/delete.html"},method={RequestMethod.GET,RequestMethod.POST}) 706 public ModelAndView deleteMember(HttpServletRequest request, HttpServletResponse response, 707 @PathVariable("id")String id){ 708 Map<String,Object> map = new HashMap<String, Object>(); 709 try { 710 this.memberService.delete(id); 711 map.put("message", "删除Id为" + id +"的用户成功."); 712 } catch (Exception e) { 713 e.printStackTrace(); 714 map.put("message", "删除Id为" + id +"的用户失败, "+e.getMessage()); 715 } 716 return toView("member/message", map); 717 } 718 719 }