欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring基于注解整合Redis完整实例

程序员文章站 2024-02-29 20:55:34
在《redis之——spring整合redis》一文中,向大家介绍了如何将spring与redis整合起来,但不是基于注解的形式,很多同学都希望能够通过注解的形式来简单的将...

在《redis之——spring整合redis》一文中,向大家介绍了如何将spring与redis整合起来,但不是基于注解的形式,很多同学都希望能够通过注解的形式来简单的将spring与redis整合起来,这样,在使用的时候,只需要在相应的方法上加上注解,便可以使方法轻松的调用redis的缓存。那么今天就来向大家介绍如何用基于注解的形式来整合spring与redis。

一、项目搭建

今天,我们不使用hibernate来操作数据库了,我们今天选择的框架是: spring4(包括mvc、context、orm) + mybatis3,所以,我们今天的基础架构是:spring4(包括mvc、context、orm) + mybatis3+redis

1、构建pom.xml

<project 
  xmlns="http://maven.apache.org/pom/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
  xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
  <modelversion>4.0.0</modelversion> 
  <groupid>lyz</groupid> 
  <artifactid>lyz</artifactid> 
  <version>1.0.0</version> 
  <packaging>war</packaging> 
  <name>lyz</name> 
  <description>basic data platform</description> 
 
  <properties> 
    <project.build.sourceencoding>utf-8</project.build.sourceencoding> 
    <spring.version>4.2.0.release</spring.version> 
  </properties> 
 
  <dependencies> 
 
    <!-- spring mvc related.....start --> <!-- todo: replace jackson with fastjson --> 
    <dependency> 
      <groupid>org.springframework</groupid> 
      <artifactid>spring-context</artifactid> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupid>org.springframework</groupid> 
      <artifactid>spring-aop</artifactid> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupid>org.springframework</groupid> 
      <artifactid>spring-webmvc</artifactid> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupid>org.springframework</groupid> 
      <artifactid>spring-web</artifactid> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupid>javax.servlet</groupid> 
      <artifactid>jstl</artifactid> 
      <version>1.2</version> 
    </dependency> 
    <dependency> 
      <groupid>commons-logging</groupid> 
      <artifactid>commons-logging</artifactid> 
      <version>1.1.3</version> 
    </dependency> 
    <dependency> 
      <groupid>org.codehaus.jackson</groupid> 
      <artifactid>jackson-mapper-asl</artifactid> 
      <version>1.9.13</version> 
    </dependency> 
    <dependency> 
      <groupid>com.fasterxml.jackson.core</groupid> 
      <artifactid>jackson-annotations</artifactid> 
      <version>2.6.1</version> 
    </dependency> 
    <dependency> 
      <groupid>com.fasterxml.jackson.core</groupid> 
      <artifactid>jackson-core</artifactid> 
      <version>2.6.1</version> 
    </dependency> 
    <dependency> 
      <groupid>com.fasterxml.jackson.core</groupid> 
      <artifactid>jackson-databind</artifactid> 
      <version>2.6.1</version> 
    </dependency> 
    <!-- spring mvc related.....end --> 
 
    <!-- mybatis orm related.....start --> 
    <dependency> 
      <groupid>org.springframework</groupid> 
      <artifactid>spring-orm</artifactid> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupid>org.mybatis</groupid> 
      <artifactid>mybatis-spring</artifactid> 
      <version>1.2.3</version> 
    </dependency> 
    <dependency> 
      <groupid>mysql</groupid> 
      <artifactid>mysql-connector-java</artifactid> 
      <version>5.1.36</version> 
    </dependency> 
    <dependency> 
      <groupid>org.mybatis</groupid> 
      <artifactid>mybatis</artifactid> 
      <version>3.3.0</version> 
    </dependency> 
    <dependency> 
      <groupid>c3p0</groupid> 
      <artifactid>c3p0</artifactid> 
      <version>0.9.1.2</version> 
    </dependency> 
    <dependency> 
      <groupid>org.slf4j</groupid> 
      <artifactid>slf4j-log4j12</artifactid> 
      <version>1.7.12</version> 
    </dependency> 
    <!-- mybatis orm related.....end --> 
 
    <!-- project log related.....start --> 
    <dependency> 
      <groupid>log4j</groupid> 
      <artifactid>log4j</artifactid> 
      <version>1.2.17</version> 
    </dependency> 
    <!-- project log related.....end --> 
 
    <!-- redis cache related.....start --> 
    <dependency> 
      <groupid>org.springframework.data</groupid> 
      <artifactid>spring-data-redis</artifactid> 
      <version>1.6.0.release</version> 
    </dependency> 
    <dependency> 
      <groupid>redis.clients</groupid> 
      <artifactid>jedis</artifactid> 
      <version>2.7.3</version> 
    </dependency> 
    <!-- redis cache related.....end --> 
  </dependencies> 
 
  <build> 
    <plugins> 
      <plugin> 
        <artifactid>maven-compiler-plugin</artifactid> 
        <version>3.1</version> 
        <configuration> 
          <source>1.7</source> 
          <target>1.7</target> 
        </configuration> 
      </plugin> 
      <plugin> 
        <artifactid>maven-war-plugin</artifactid> 
        <version>2.4</version> 
        <configuration> 
          <warsourcedirectory>webcontent</warsourcedirectory> 
          <failonmissingwebxml>false</failonmissingwebxml> 
        </configuration> 
      </plugin> 
    </plugins> 
  </build> 
</project> 

2、创建测试数据库:lyz,测试数据表:user

drop database if exists `lyz`; 
create database `lyz`; 
drop table if exists `user`; 
create table `user` ( 
 `id` int(10) unsigned not null auto_increment, 
 `name` varchar(255) default null, 
 `sex` varchar(255) default null, 
 `age` int(11) default null, 
 primary key (`id`) 
) engine=innodb default charset=utf8; 

3、创建实体类user

package com.lyz.user.bean; 
 
import java.io.serializable; 
 
import org.codehaus.jackson.map.annotate.jsonserialize; 
 
import com.fasterxml.jackson.databind.propertynamingstrategy; 
import com.fasterxml.jackson.databind.annotation.jsonnaming; 
 
/** 
 * 用户实体类 
 * @author liuyazhuang 
 * 
 */ 
@jsonserialize 
@jsonnaming(propertynamingstrategy.lowercasewithunderscoresstrategy.class)  
public class user implements serializable{ 
  private static final long serialversionuid = 1332643889208978231l; 
   
  /** 
   * id 
   */ 
  private integer id; 
   
  /** 
   * 姓名 
   */ 
  private string name; 
   
  /** 
   * 性别 
   */ 
  private string sex; 
   
  /** 
   * 年龄 
   */ 
  private integer age; 
 
  public user() { 
    super(); 
  } 
   
  public user(integer id, string name) { 
    super(); 
    this.id = id; 
    this.name = name; 
  } 
 
  public user(string name, string sex, integer age) { 
    super(); 
    this.name = name; 
    this.sex = sex; 
    this.age = age; 
  } 
 
  public integer getid() { 
    return id; 
  } 
 
  public void setid(integer id) { 
    this.id = id; 
  } 
 
  public string getname() { 
    return name; 
  } 
 
  public void setname(string name) { 
    this.name = name; 
  } 
 
  public string getsex() { 
    return sex; 
  } 
 
  public void setsex(string sex) { 
    this.sex = sex; 
  } 
 
  public integer getage() { 
    return age; 
  } 
 
  public void setage(integer age) { 
    this.age = age; 
  } 
 
  @override 
  public string tostring() { 
    return "user [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]"; 
  } 
   
} 

4、创建usermapper接口

此接口定义了与mybatis交互的接口协议,通过此接口与mybatis框架通信,由mybatis框架实现对数据库的增删改查操作。

package com.lyz.user.mapper; 
 
import java.util.list; 
 
import com.lyz.user.bean.user; 
 
/** 
 * usermapper接口 
 * @author liuyazhuang 
 * 
 */ 
public interface usermapper { 
   
  /** 
   * 保存用户 
   * @param user 
   */ 
  void saveuser(user user); 
   
  /** 
   * 获取所有用户列表 
   * @return 
   */ 
  list<user> getalluser(); 
   
  /** 
   * 根据id查询用户信息 
   * @param id 
   * @return 
   */ 
  user getuserbyid(integer id); 
   
  /** 
   * 更新用户的名称 
   * @param user 
   */ 
  void renameuser(user user); 
   
  /** 
   * 根据id删除指定的用户 
   * @param id 
   */ 
  void deleteuserbyid(integer id); 
} 

5、创建usermapper.xml

此文件中主要实现了usermapper接口定义的方法,即实现对数据库的增删改查操作。

<?xml version="1.0" encoding="utf-8" ?> 
<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 
<mapper namespace="com.lyz.user.mapper.usermapper" > 
 
  <!-- 插入一条城市记录 --> 
  <insert id="saveuser" parametertype="com.lyz.user.bean.user"> 
    insert into user (name, sex, age) 
    values ( #{name}, #{sex}, #{age} ) 
  </insert> 
 
  <!-- 根据省份名称返回该省份下的所有城市列表 --> 
  <select id="getalluser" resulttype="com.lyz.user.bean.user"> 
    select u.id, u.name, u.sex, u.age from user u   
  </select> 
   
  <!-- 根据 city_code 查找城市信息 --> 
  <select id="getuserbyid" resulttype="com.lyz.user.bean.user" parametertype="java.lang.integer"> 
    select u.id, u.name, u.sex, u.age from user u where u.id = #{id} 
  </select> 
   
  <!-- 重命名城市 -->  
  <update id="renameuser" parametertype="com.lyz.user.bean.user"> 
    update user set name = #{name} where id = #{id} 
  </update>  
   
  <!-- 删除一个城市记录 -->  
  <delete id="deleteuserbyid" parametertype="java.lang.integer">  
    delete from user where id = #{id}  
  </delete>  
</mapper> 

6、创建userdao接口

package com.lyz.user.dao; 
 
import java.util.list; 
 
import com.lyz.user.bean.user; 
 
/** 
 * 用户dao接口 
 * @author liuyazhuang 
 * 
 */ 
public interface userdao { 
   /** 
   * 保存用户 
   * @param user 
   */ 
  void saveuser(user user); 
   
  /** 
   * 获取所有用户列表 
   * @return 
   */ 
  list<user> getalluser(); 
   
  /** 
   * 根据id查询用户信息 
   * @param id 
   * @return 
   */ 
  user getbyid(integer id); 
   
  /** 
   * 更新用户的名称 
   * @param user 
   */ 
  void rename(user user); 
   
  /** 
   * 根据id删除指定的用户 
   * @param id 
   */ 
  void deletebyid(integer id); 
} 

7、创建userdao的实现类userdaoimpl

此类主要实现userdao中定义的接口,主要实现方法是注入usermapper接口的实例对象,调用usermapper接口实例的方法来实现相应的操作。

package com.lyz.user.dao.impl; 
import java.util.list;  
import javax.annotation.resource;  
import org.springframework.stereotype.repository;  
import com.lyz.user.bean.user; 
import com.lyz.user.dao.userdao; 
import com.lyz.user.mapper.usermapper; 
/** 
 * dao实现类 
 * @author liuyazhuang 
 * 
 */ 
@repository 
public class userdaoimpl implements userdao { 
  @resource 
  private usermapper musermapper; 
   
  @override 
  public void saveuser(user user) { 
    musermapper.saveuser(user); 
  } 
 
  @override 
  public list<user> getalluser() { 
    return musermapper.getalluser(); 
  } 
 
  @override 
  public user getbyid(integer id) { 
    return musermapper.getuserbyid(id); 
  } 
 
  @override 
  public void rename(user user) { 
    musermapper.renameuser(user); 
  } 
 
  @override 
  public void deletebyid(integer id) { 
    musermapper.deleteuserbyid(id); 
  } 
 
 
} 

8、创建userservice接口

package com.lyz.user.service;  
import java.util.list;  
import com.lyz.user.bean.user;  
/** 
 * 用户service接口 
 * @author liuyazhuang 
 * 
 */ 
public interface userservice { 
   /** 
   * 保存用户 
   * @param user 
   */ 
  void saveuser(string name, string sex, integer age); 
   
  /** 
   * 获取所有用户列表 
   * @return 
   */ 
  list<user> getalluser(); 
   
  /** 
   * 根据id查询用户信息 
   * @param id 
   * @return 
   */ 
  user getuserbyid(integer id); 
   
  /** 
   * 更新用户的名称 
   * @param user 
   */ 
  void renameuser(string name, integer id); 
   
  /** 
   * 根据id删除指定的用户 
   * @param id 
   */ 
  void deleteuserbyid(integer id); 
} 

9、创建userservice接口实现类userserviceimpl

package com.lyz.user.service.impl; 
import java.util.list;  
import javax.annotation.resource;  
import org.springframework.cache.annotation.cacheevict; 
import org.springframework.cache.annotation.cacheable; 
import org.springframework.stereotype.service; 
import org.springframework.transaction.annotation.propagation; 
import org.springframework.transaction.annotation.transactional; 
import com.lyz.user.bean.user; 
import com.lyz.user.dao.userdao; 
import com.lyz.user.service.userservice; 
/** 
 * userservice实现类 
 * @author liuyazhuang 
 * 
 */ 
@service 
@transactional(propagation=propagation.required, rollbackfor=exception.class) 
public class userserviceimpl implements userservice { 
  @resource 
  private userdao muserdao; 
   
  @override 
  @cacheevict(value = { "saveuser"}, allentries = true) 
  public void saveuser(string name, string sex, integer age) { 
    user user = new user(name, sex, age); 
    muserdao.saveuser(user); 
  } 
 
  @override 
  @cacheable("getalluser") 
  public list<user> getalluser() { 
    return muserdao.getalluser(); 
  } 
 
  @override 
  @cacheable("getuserbyid") 
  public user getuserbyid(integer id) { 
    return muserdao.getbyid(id); 
  } 
 
  @override 
  @cacheevict(value = { "getalluser", "getuserbyid" }, allentries = true) 
  public void renameuser(string name, integer id) { 
    muserdao.rename(new user(id, name)); 
  } 
 
  @override 
  @cacheevict(value = { "getalluser", "getuserbyid" }, allentries = true) 
  public void deleteuserbyid(integer id) { 
    muserdao.deletebyid(id); 
  } 
 
} 

10、创建usercontroller

package com.lyz.user.controller;  
import java.util.list;  
import org.apache.commons.logging.log; 
import org.apache.commons.logging.logfactory; 
import org.springframework.beans.factory.annotation.autowired; 
import org.springframework.stereotype.controller; 
import org.springframework.web.bind.annotation.requestmapping; 
import org.springframework.web.bind.annotation.requestparam; 
import org.springframework.web.bind.annotation.responsebody; 
import com.lyz.user.bean.user; 
import com.lyz.user.service.userservice;  
/** 
 * usercontroller类 
 * @author liuyazhuang 
 * 
 */ 
@controller 
@requestmapping("/user") 
public class usercontroller { 
  private final log logger = logfactory.getlog(this.getclass()); 
  @autowired 
  private userservice muserservice; 
   
  /** 
   * 保存用户 
   * @param name 
   * @param sex 
   * @param age 
   * @return 
   */ 
  @requestmapping("/save") 
  @responsebody 
  public integer save(@requestparam(value="name", defaultvalue="") string name, 
      @requestparam(value="sex", defaultvalue="") string sex, 
      @requestparam(value="age", defaultvalue="0") string age){ 
    logger.debug(name); 
    muserservice.saveuser(name, sex, integer.parseint(age)); 
    return 1; 
  } 
   
  /** 
   * 获取所有用户列表 
   * @return 
   */ 
  @requestmapping("/getall") 
  @responsebody 
  public object getalluser(){ 
    list<user> users = muserservice.getalluser(); 
    for(user u : users){ 
      logger.debug(u.tostring()); 
    } 
    return users; 
  } 
  /** 
   * 根据用户id获取用户信息 
   * @return 
   */ 
  @requestmapping("/getuserbyid") 
  @responsebody 
  public object getuserbyid(@requestparam(value="id", defaultvalue="0") string id){ 
    user user = muserservice.getuserbyid(integer.parseint(id)); 
    logger.debug(user.tostring()); 
    return user; 
  } 
   
  /** 
   * 根据用户id获取用户信息 
   * @return 
   */ 
  @requestmapping("/renameuser") 
  @responsebody 
  public integer renameuser(@requestparam(value="id", defaultvalue="0") string id,  
               @requestparam(value="name", defaultvalue="") string name){ 
    logger.debug(id + "=========" + name); 
    muserservice.renameuser(name, integer.parseint(id)); 
    return 1; 
  } 
  /** 
   * 根据用户id获取用户信息 
   * @return 
   */ 
  @requestmapping("/delete") 
  @responsebody 
  public integer delete(@requestparam(value="id", defaultvalue="0") string id){ 
    logger.debug(id); 
    muserservice.deleteuserbyid(integer.parseint(id)); 
    return 1; 
  } 
} 

到此,只要再创建相应的配置文件,我们就可以实现spring+mybatis框架的整合了,下面我们创建一个整合redis的关键类rediscacheconfig,这个类继承cachingconfigurersupport。

11、创建rediscacheconfig类

package com.lyz.cache.redis;  
import java.lang.reflect.method;  
import org.springframework.cache.cachemanager; 
import org.springframework.cache.annotation.cachingconfigurersupport; 
import org.springframework.cache.annotation.enablecaching; 
import org.springframework.cache.interceptor.keygenerator; 
import org.springframework.context.annotation.bean; 
import org.springframework.context.annotation.configuration; 
import org.springframework.data.redis.cache.rediscachemanager; 
import org.springframework.data.redis.connection.redisconnectionfactory; 
import org.springframework.data.redis.connection.jedis.jedisconnectionfactory; 
import org.springframework.data.redis.core.redistemplate; 
 
/** 
 * 以spring与配置文件来管理的redis缓存配置类 
 * @author liuyazhuang 
 * 
 */ 
@configuration 
@enablecaching 
public class rediscacheconfig extends cachingconfigurersupport { 
   
  private volatile jedisconnectionfactory mjedisconnectionfactory; 
  private volatile redistemplate<string, string> mredistemplate; 
  private volatile rediscachemanager mrediscachemanager; 
   
  public rediscacheconfig() { 
    super(); 
  } 
 
  public rediscacheconfig(jedisconnectionfactory mjedisconnectionfactory, redistemplate<string,string> mredistemplate, 
      rediscachemanager mrediscachemanager) { 
    super(); 
    this.mjedisconnectionfactory = mjedisconnectionfactory; 
    this.mredistemplate = mredistemplate; 
    this.mrediscachemanager = mrediscachemanager; 
  } 
 
  public jedisconnectionfactory redisconnectionfactory() { 
    return mjedisconnectionfactory; 
  } 
 
  public redistemplate<string, string> redistemplate(redisconnectionfactory cf) { 
    return mredistemplate; 
  } 
 
  public cachemanager cachemanager(redistemplate<?, ?> redistemplate) { 
    return mrediscachemanager; 
  } 
   
  @bean 
  public keygenerator customkeygenerator() { 
    return new keygenerator() { 
      @override 
      public object generate(object o, method method, object... objects) { 
        stringbuilder sb = new stringbuilder(); 
        sb.append(o.getclass().getname()); 
        sb.append(method.getname()); 
        for (object obj : objects) { 
          sb.append(obj.tostring()); 
        } 
        return sb.tostring(); 
      } 
    }; 
  } 
} 

这个类中的所有属性、字段都是在spring的配置文件lyz-applicationcontext.xml文件中注入的,稍后我们介绍如何注入这些属性字段。

下面介绍每个配置文件的内容,注:所有的配置文件(除了web.xml),都是放在classpath路径下的。

12、创建数据库的配置文件jdbc.properties

jdbc.host=127.0.0.1 
jdbc.database=lyz 
jdbc.port=3306 
jdbc.username=root 
jdbc.password=root 

13、创建log4j日志配置文件log4j.properties

# global logging configuration 
log4j.rootlogger=warn,stdout 
# console output... 
log4j.appender.stdout=org.apache.log4j.consoleappender 
log4j.appender.stdout.layout=org.apache.log4j.patternlayout 
log4j.appender.stdout.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:ss} %-5p %c:%l - %m%n 
# mybatis log 
log4j.logger.com.lyz.user.mapper.usermapper=debug 
# lyz log 
log4j.logger.com.lyz.user.controller=debug 
log4j.logger.com.lyz.user.service=debug 

14、创建redis配置文件redis.properties

# redis settings 
redis.host=192.168.157.130 
redis.port=6379 
redis.pass=liuyazhuang 
redis.dbindex=0 
redis.expiration=3000  
redis.maxidle=300 
redis.maxactive=600 
redis.maxwait=1000 
redis.testonborrow=true 

15、创建springmvc的配置文件lyzmvc-servlet.xml

<?xml version="1.0" encoding="utf-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:p="http://www.springframework.org/schema/p" 
  xmlns:context="http://www.springframework.org/schema/context" 
  xsi:schemalocation="http://www.springframework.org/schema/beans 
  
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
http://www.springframework.org/schema/context  
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 
  
  <!-- class annotation related... start --> 
  <context:component-scan base-package="com.lyz.*.controller" /> 
  <!-- class annotation related... end --> 
  
  <!-- jsp page related... start --> 
  <bean id="viewresolver" 
    class="org.springframework.web.servlet.view.urlbasedviewresolver"> 
    <property name="viewclass" 
      value="org.springframework.web.servlet.view.jstlview" /> 
    <property name="prefix" value="/web-inf/jsp/" /> 
    <property name="suffix" value=".jsp" /> 
  </bean> 
  <!-- jsp page related... end --> 
   
  <!-- rest json related... start --> 
  <bean id="mappingjacksonhttpmessageconverter" 
     class="org.springframework.http.converter.json.mappingjackson2httpmessageconverter"> 
    <property name="supportedmediatypes"> 
      <list> 
        <value>application/json;charset=utf-8</value> 
      </list> 
    </property> 
  </bean> 
  <bean class="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter"> 
    <property name="messageconverters"> 
      <list> 
        <ref bean="mappingjacksonhttpmessageconverter"/> 
      </list> 
    </property> 
  </bean> 
  <!-- rest json related... end --> 
</beans> 

16、创建mybatis配置文件mybatis-config.xml

<?xml version="1.0" encoding="utf-8"?> 
<!doctype configuration public "-//mybatis.org//dtd config 3.0//en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration> 
  <settings> 
    <setting name="mapunderscoretocamelcase" value="true"/> 
  </settings> 
</configuration> 

17、创建spring核心配置文件lyz-applicationcontext.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"  
  xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:aop="http://www.springframework.org/schema/aop"  
  xmlns:tx="http://www.springframework.org/schema/tx" 
  xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 
   <!-- class annotation related... start --> 
  <context:component-scan base-package="com.lyz"/>   
  <context:component-scan base-package="com.lyz.*.service" /> 
  <context:component-scan base-package="com.lyz.*.service.*" /> 
  <context:component-scan base-package="com.lyz.cache.redis" /> 
  <!-- class annotation related... end --> 
  <context:annotation-config /> 
  <!-- mybatis related... start --> 
  <bean class="org.springframework.beans.factory.config.propertyplaceholderconfigurer"> 
    <property name="locations"> 
      <list> 
        <!-- 这里支持多种寻址方式:classpath和file --> 
        <value>classpath:jdbc.properties</value> 
        <value>classpath:redis.properties</value> 
        <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 --> 
      </list> 
    </property> 
  </bean> 
  <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource " 
    destroy-method="close"> 
    <property name="driverclass" value="com.mysql.jdbc.driver" /> 
    <property name="jdbcurl" value="jdbc:mysql://${jdbc.host}:${jdbc.port}/${jdbc.database}?useunicode=true&characterencoding=utf8" /> 
    <property name="user" value="${jdbc.username}" /> 
    <property name="password" value="${jdbc.password}" /> 
    <property name="acquireincrement" value="1" /> 
    <property name="initialpoolsize" value="5" /> 
    <property name="maxpoolsize" value="20" /> 
    <property name="minpoolsize" value="5" /> 
    <property name="maxstatements" value="100" /> 
    <property name="testconnectiononcheckout" value="true" /> 
  </bean> 
  <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> 
    <property name="datasource" ref="datasource" /> 
    <property name="configlocation" value="/web-inf/classes/mybatis-config.xml" /> 
  </bean> 
  <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"> 
    <property name="basepackage" value="com.lyz.*.mapper"/> 
  </bean> 
  <!-- mybatis related... end --> 
 
  <!-- transaction config related... start --> 
  <tx:annotation-driven transaction-manager="transactionmanager" /> 
  <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"> 
    <property name="datasource" ref="datasource" /> 
  </bean> 
  <!-- transaction config related... end --> 
   
  <!-- redis config start --> 
  <!-- 配置jedispoolconfig实例 --> 
  <bean id="poolconfig" class="redis.clients.jedis.jedispoolconfig"> 
    <property name="maxidle" value="${redis.maxidle}" /> 
    <property name="maxtotal" value="${redis.maxactive}" /> 
    <property name="maxwaitmillis" value="${redis.maxwait}" /> 
    <property name="testonborrow" value="${redis.testonborrow}" /> 
  </bean> 
   
  <!-- 配置jedisconnectionfactory --> 
  <bean id="jedisconnectionfactory" class="org.springframework.data.redis.connection.jedis.jedisconnectionfactory"> 
    <property name="hostname" value="${redis.host}"/> 
    <property name="port" value="${redis.port}"/> 
    <property name="password" value="${redis.pass}"/> 
    <property name="database" value="${redis.dbindex}"/> 
    <property name="poolconfig" ref="poolconfig"/> 
  </bean> 
   
  <!-- 配置redistemplate --> 
  <bean id="redistemplate" class="org.springframework.data.redis.core.redistemplate"> 
    <property name="connectionfactory" ref="jedisconnectionfactory"/> 
  </bean> 
   
  <!-- 配置rediscachemanager --> 
  <bean id="rediscachemanager" class="org.springframework.data.redis.cache.rediscachemanager"> 
     <constructor-arg name="redisoperations" ref="redistemplate" /> 
    <property name="defaultexpiration" value="${redis.expiration}"/> 
  </bean> 
   
  <!-- 配置rediscacheconfig --> 
  <bean id="rediscacheconfig" class="com.lyz.cache.redis.rediscacheconfig"> 
    <constructor-arg ref="jedisconnectionfactory" /> 
    <constructor-arg ref="redistemplate" /> 
    <constructor-arg ref="rediscachemanager" /> 
  </bean> 
   
  <!-- redis config end --> 
   
</beans> 

注:在lyz-applicationcontext.xml配置文件中,配置了spring的注解、注入了rediscacheconfig中的属性字段。

18、完善web.xml文件

<?xml version="1.0" encoding="utf-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
  xmlns="http://java.sun.com/xml/ns/javaee" 
  xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
  id="webapp_id" version="3.0"> 
  <display-name>lyz</display-name> 
   
  <!-- character encoding related.....start --><!-- todo : 将 encodingfilter、sysparamsfilter 两个过滤器交给 spring 管理 --> 
  <filter> 
    <filter-name>encodingfilter</filter-name> 
    <filter-class> 
        org.springframework.web.filter.characterencodingfilter  
    </filter-class> 
    <init-param> 
        <param-name>encoding</param-name> 
        <param-value>utf-8</param-value> 
    </init-param> 
    <init-param> 
        <param-name>forceencoding</param-name> 
        <param-value>true</param-value> 
    </init-param> 
  </filter> 
  <filter-mapping> 
     <filter-name>encodingfilter</filter-name> 
     <url-pattern>/*</url-pattern> 
  </filter-mapping> 
  <!-- 除了加过滤器,由于tomcat默认编码iso-8859-1,还需要修改 %tomcat%/conf/server.xml connector 标签加属性 uriencoding="utf-8" --> 
  <!-- character encoding related.....end --> 
 
  <context-param> 
    <param-name>contextconfiglocation</param-name> 
    <param-value>/web-inf/classes/*-applicationcontext.xml</param-value> 
  </context-param> 
  <listener> 
    <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> 
  </listener> 
 
  <servlet> 
    <servlet-name>lyzmvc</servlet-name> 
    <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> 
    <init-param> 
      <param-name>contextconfiglocation</param-name> 
      <param-value>/web-inf/classes/*-servlet.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
  </servlet> 
  <servlet-mapping> 
    <servlet-name>lyzmvc</servlet-name> 
    <url-pattern>*.json</url-pattern> 
    <url-pattern>*.html</url-pattern> 
  </servlet-mapping> 
</web-app> 

二、运行测试

这里我们使用apache jmeter来测试我们的程序,大家可以到下载apache jmeter。

1、启动程序,使用jmeter调用保存用户接口

首先按照图示配置jmeter,其中访问路径和端口按照实际需要配置:

Spring基于注解整合Redis完整实例

点击启动按钮,也就是上方的

Spring基于注解整合Redis完整实例

图标:

点击“查看结果树”并打开“响应数据”选项:

Spring基于注解整合Redis完整实例

我们看到返回的结果是1,证明我们成功的调用了保存用户的接口。

下面我们来看看数据库表:

Spring基于注解整合Redis完整实例

已经将数据保存到数据库了。

2、调用查询用户的接口

首先按照图示配置jmeter,其中访问路径和端口按照实际需要配置:

Spring基于注解整合Redis完整实例

这些我们先看看redis服务器中是否存在相应的数据:

Spring基于注解整合Redis完整实例

此时,redis服务器中并没有任何数据,下面我们点击启动,执行程序:

点击“查看结果数”并打开“响应数据”,如下:

Spring基于注解整合Redis完整实例

返回了相应的数据。

我们再打开控制台看看输出的语句:

Spring基于注解整合Redis完整实例

说明首次获取数据是从数据库中获取的。下面我们再看看redis缓存中是否存在数据了:

Spring基于注解整合Redis完整实例

说明首次获取数据,从数据库中取出的数据已经放在了redis缓存服务器中。

我们再次点击jmeter的启动按钮,执行查询用户的操作:

查看jmeter的“查看结果数”中的“响应数据”选项:

Spring基于注解整合Redis完整实例

返回了正确的结果,同时,我们再看看eclipse的控制台:

Spring基于注解整合Redis完整实例

已经没有再从数据库中获取数据了,说明再次执行查询用户的操作,程序是直接从redis缓存中获取的数据。

至此,spring基于注解整合redis介绍完毕。

三、源码下载

完整示例代码:spring_redis_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。