溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發(fā)布時間:2020-09-26 10:55:10 來源:腳本之家 閱讀:371 作者:liuyazhuang 欄目:編程語言

在《Redis之——Spring整合Redis》一文中,向大家介紹了如何將spring與Redis整合起來,但不是基于注解的形式,很多同學都希望能夠通過注解的形式來簡單的將Spring與Redis整合起來,這樣,在使用的時候,只需要在相應的方法上加上注解,便可以使方法輕松的調用Redis的緩存。那么今天就來向大家介紹如何用基于注解的形式來整合Spring與Redis。

一、項目搭建

今天,我們不使用hibernate來操作數(shù)據(jù)庫了,我們今天選擇的框架是: 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、創(chuàng)建測試數(shù)據(jù)庫:lyz,測試數(shù)據(jù)表: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、創(chuàng)建實體類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、創(chuàng)建UserMapper接口

此接口定義了與MyBatis交互的接口協(xié)議,通過此接口與MyBatis框架通信,由MyBatis框架實現(xiàn)對數(shù)據(jù)庫的增刪改查操作。

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(); 
   
  /** 
   * 根據(jù)id查詢用戶信息 
   * @param id 
   * @return 
   */ 
  User getUserById(Integer id); 
   
  /** 
   * 更新用戶的名稱 
   * @param user 
   */ 
  void renameUser(User user); 
   
  /** 
   * 根據(jù)id刪除指定的用戶 
   * @param id 
   */ 
  void deleteUserById(Integer id); 
} 

5、創(chuàng)建UserMapper.xml

此文件中主要實現(xiàn)了UserMapper接口定義的方法,即實現(xiàn)對數(shù)據(jù)庫的增刪改查操作。

<?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> 
 
  <!-- 根據(jù)省份名稱返回該省份下的所有城市列表 --> 
  <select id="getAllUser" resultType="com.lyz.user.bean.User"> 
    select u.id, u.name, u.sex, u.age from user u   
  </select> 
   
  <!-- 根據(jù) 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、創(chuàng)建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(); 
   
  /** 
   * 根據(jù)id查詢用戶信息 
   * @param id 
   * @return 
   */ 
  User getById(Integer id); 
   
  /** 
   * 更新用戶的名稱 
   * @param user 
   */ 
  void rename(User user); 
   
  /** 
   * 根據(jù)id刪除指定的用戶 
   * @param id 
   */ 
  void deleteById(Integer id); 
} 

7、創(chuàng)建UserDao的實現(xiàn)類UserDaoImpl

此類主要實現(xiàn)UserDao中定義的接口,主要實現(xiàn)方法是注入UserMapper接口的實例對象,調用UserMapper接口實例的方法來實現(xiàn)相應的操作。

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實現(xiàn)類 
 * @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、創(chuàng)建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(); 
   
  /** 
   * 根據(jù)id查詢用戶信息 
   * @param id 
   * @return 
   */ 
  User getUserById(Integer id); 
   
  /** 
   * 更新用戶的名稱 
   * @param user 
   */ 
  void renameUser(String name, Integer id); 
   
  /** 
   * 根據(jù)id刪除指定的用戶 
   * @param id 
   */ 
  void deleteUserById(Integer id); 
} 

9、創(chuàng)建UserService接口實現(xiàn)類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實現(xiàn)類 
 * @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、創(chuàng)建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; 
  } 
  /** 
   * 根據(jù)用戶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; 
  } 
   
  /** 
   * 根據(jù)用戶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; 
  } 
  /** 
   * 根據(jù)用戶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; 
  } 
} 

到此,只要再創(chuàng)建相應的配置文件,我們就可以實現(xiàn)Spring+MyBatis框架的整合了,下面我們創(chuàng)建一個整合Redis的關鍵類RedisCacheConfig,這個類繼承CachingConfigurerSupport。

11、創(chuàng)建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、創(chuàng)建數(shù)據(jù)庫的配置文件jdbc.properties

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

13、創(chuàng)建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、創(chuàng)建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、創(chuàng)建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、創(chuàng)建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、創(chuàng)建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完整實例

圖標:

點擊“查看結果樹”并打開“響應數(shù)據(jù)”選項:

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

我們看到返回的結果是1,證明我們成功的調用了保存用戶的接口。

下面我們來看看數(shù)據(jù)庫表:

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

已經將數(shù)據(jù)保存到數(shù)據(jù)庫了。

2、調用查詢用戶的接口

首先按照圖示配置JMeter,其中訪問路徑和端口按照實際需要配置:

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

這些我們先看看redis服務器中是否存在相應的數(shù)據(jù):

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

此時,redis服務器中并沒有任何數(shù)據(jù),下面我們點擊啟動,執(zhí)行程序:

點擊“查看結果數(shù)”并打開“響應數(shù)據(jù)”,如下:

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

返回了相應的數(shù)據(jù)。

我們再打開控制臺看看輸出的語句:

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

說明首次獲取數(shù)據(jù)是從數(shù)據(jù)庫中獲取的。下面我們再看看redis緩存中是否存在數(shù)據(jù)了:

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

說明首次獲取數(shù)據(jù),從數(shù)據(jù)庫中取出的數(shù)據(jù)已經放在了redis緩存服務器中。

我們再次點擊Jmeter的啟動按鈕,執(zhí)行查詢用戶的操作:

查看Jmeter的“查看結果數(shù)”中的“響應數(shù)據(jù)”選項:

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

返回了正確的結果,同時,我們再看看Eclipse的控制臺:

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

已經沒有再從數(shù)據(jù)庫中獲取數(shù)據(jù)了,說明再次執(zhí)行查詢用戶的操作,程序是直接從Redis緩存中獲取的數(shù)據(jù)。

至此,Spring基于注解整合Redis介紹完畢。

三、源碼下載

完整示例代碼:Spring_Redis_jb51.rar

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI