redis与springmvc的集成

本文介绍了如何在Spring MVC项目中集成Redis作为缓存工具。首先,需要添加jedis和相关依赖到项目中。接着,配置redis.properties文件并设置连接参数。然后,在app.xml中配置Redis连接对象。最后,在DAO实现类中添加Redis操作方法,如添加和查看对象。通过这些步骤,可以实现在业务处理中与Redis的交互。
摘要由CSDN通过智能技术生成

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.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
        
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.4.2</version>
</dependency>
        
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.6.0.RELEASE</version>
</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">
        
        
    <!--spring注解驱动-->
    <context:annotation-config></context:annotation-config>
    <!--组件扫描的范围-->
    <context:component-scan base-package="cn.sz.gl"></context:component-scan>
    
    
    <!-- <context:property-placeholder location="classpath:jdbc.properties" /> -->
    <!--上述方法只能引入单个properties文件,要想引入多个properties文件,可以采用如下方式-->
    <bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <value>classpath:redis.properties</value>
            </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注解驱动 -->
    <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>

     <!--spring事务处理对象-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>
    <!--spring事务的注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager" /> 
    
 
    <!-- 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="poolConfig" ref="poolConfig"/>  
    </bean>  
      
    <!-- 配置RedisTemplate -->  
    <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数据库的交互。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值