温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-26 10:55:10 来源:脚本之家 阅读:381 作者:liuyazhuang 栏目:编程语言

在《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来测试我们的程序,大家可以到http://jmeter.apache.org/download_jmeter.cgi下载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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI