redis与springmvc的集成

redis是现在主流的缓存工具了,因为使用简单、高效且对服务器要求较小,用于大数据量下的缓存,spring 也提供了对redis的支持: org.springframework.data.redis.core.RedisTemplate。为了在springmvc环境中使用redis,官方推荐是和jedis结合使用,由jedis来管理连接这些。

1. 添加支持

​ 首先需要为项目添加redis的支持,需要添加的jar包有三个:

​ commons-pool2-2.4.2.jar

​ jedis-2.9.0.jar

​ spring-data-redis-1.6.0.RELEASE.jar

​ 如果是maven项目,需要添加的依赖如下:

<dependency>
    <groupId>redis.clientsgroupId>
    <artifactId>jedisartifactId>
    <version>2.9.0version>
dependency>
        
<dependency>
    <groupId>org.apache.commonsgroupId>
    <artifactId>commons-pool2artifactId>
    <version>2.4.2version>
dependency>
        
<dependency>
    <groupId>org.springframework.datagroupId>
    <artifactId>spring-data-redisartifactId>
    <version>1.6.0.RELEASEversion>
dependency>

2.spring整合redis

先准备redis.properties文件,存放redis连接参数,文件内容如下:


redis.host=10.3.12.250
redis.port=6379
redis.pass=123
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true

在springmvc配置文件app.xml中,配置redis连接对象,配置信息如下:

xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
    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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
        
        
    
    <context:annotation-config>context:annotation-config>
    
    <context:component-scan base-package="cn.sz.gl">context:component-scan>
    
    
    
    
    <bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
        <property name="locations">
            <list>
                <value>classpath:jdbc.propertiesvalue>
                <value>classpath:redis.propertiesvalue>
            list>
        property>
    bean>
    
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
        <property name="driverClassName" value="${mydriver}">property>
        <property name="url" value="${myurl}">property>
        <property name="username" value="${myuser}" >property>
        <property name="password" value="${mypwd}" >property>
    bean>
    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
        <property name="dataSource" ref="dataSource" >property>
        <property name="configLocation" value="classpath:mybatis_config.xml" >property>
    bean>
    
    
    <mvc:annotation-driven>mvc:annotation-driven>
    
    <bean id="irv" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix" value="/" >property>
        <property name="suffix" value=".jsp" >property>
    bean>

     
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" /> 
    
 
      
      
    <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>  
      
      
    <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="poolConfig" ref="poolConfig"/>  
    bean>  
      
      
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> 
    <property name="connectionFactory"   ref="jedisConnectionFactory" /> 
  bean>
      
beans>

3.DAO实现类中,添加操作方法

​ 在DAO实现了中,添加redis数据库调用方法,这里往redis数据库中添加和查看一个对象的方法,代码如下:


package cn.sz.gl.dao.impl;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import cn.sz.gl.dao.IDeptDAO;
import cn.sz.gl.pojo.Dept;
@Repository
public class DeptDAOImpl extends SqlSessionDaoSupport implements IDeptDAO {

    private RedisTemplate<String, Dept> redisTemplate;
    
    @Override
    public boolean addRedis(final Dept vo) {
        boolean flag = redisTemplate.execute(new RedisCallback<Boolean>() {

            @Override
            public Boolean doInRedis(RedisConnection connection)
                    throws DataAccessException {
                 connection.hSet(("dept:"+vo.getDeptno()).getBytes(), "deptno".getBytes(), (vo.getDeptno()+"").getBytes());
                 connection.hSet(("dept:"+vo.getDeptno()).getBytes(), "dname".getBytes(), vo.getDname().getBytes());
                //return connection.setNX((vo.getDeptno()+"").getBytes(), vo.getDname().getBytes());
                 return true;
            }
        });
        return flag;
    }
    
    @Override
    public Dept findByRedis(final String id) {
        Dept dept = redisTemplate.execute(new RedisCallback<Dept>() {

            @Override
            public Dept doInRedis(RedisConnection connection)
                    throws DataAccessException {
                /*byte [] bs = connection.get(id.getBytes());
                String dname = new String(bs);*/
                
                byte [] bs_no = connection.hGet(("dept:"+id).getBytes(), "deptno".getBytes());
                byte [] bs_name = connection.hGet(("dept:"+id).getBytes(), "dname".getBytes());
                
                Integer dno = Integer.valueOf(new String(bs_no));
                String dname = new String(bs_name);
                Dept d = new Dept();
                d.setDeptno(Integer.valueOf(id));
                d.setDname(dname);
                return d;
            }
        });
        return dept;
    }
    
    

    public RedisTemplate<String, Dept> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<String, Dept> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}

​ 至此,配置完成,在业务处理过程中,如果调用了DAO中上述方法,即可实现与redis数据库的交互。

你可能感兴趣的:(Redis)