Spring下redis的配置

这个项目用到redis,所以学了一下怎样在Spring框架下配置redis。

1、首先是在web.xml中添加Spring的配置文件。

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>common design</display-name>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webapp.root</param-value>
    </context-param> 

    <!-- 添加Spring mybatis的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml,classpath*:mybatis-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
  </servlet>

  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
     <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>

2、然后是redis的配置文件(redis-config.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
     http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd"
    default-autowire="byName" default-lazy-init="true">

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
    <!-- redis服务器中心 -->
    <bean id="connectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig" />
        <property name="port" value="${redis.port}" />
        <property name="hostName" value="${redis.host}" />
        <property name="password" value="${redis.password}" />
        <property name="timeout" value="${redis.timeout}"></property>
    </bean>
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="keySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean>

    <bean id="redisUtil" class="com.zkxl.fep.redis.RedisUtil">
        <property name="redisTemplate" ref="redisTemplate" />
    </bean>

</beans>

在Spring的配置文件中引用redis的配置文件

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
     http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd"
    default-autowire="byName" default-lazy-init="true">

    <context:annotation-config/>
    <context:component-scan base-package="com.test.fep" />

    <!-- 增加redis的properties文件 -->
    <context:property-placeholder location="classpath*:jdbc.properties,classpath*:redis.properties" />

    <import resource="datasource.xml"/>
    <!-- 导入redis的配置文件 -->
    <import resource="redis-config.xml"/>

</beans>

3、新建redis.properties,里面包含redis连接需要的配置信息

#redis setting
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
redis.maxIdle=100
redis.maxActive=300
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000

fep.local.cache.capacity =10000

一定要注意,每行后面千万不要有空格,我就是因为这个问题卡了一两个小时= =

4、编写RedisUtil.java,里面放有redis的增删改查操作。

package com.test.fep.redis;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;  

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;  

public class RedisUtil {

    private RedisTemplate<Serializable, Object> redisTemplate;

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            logger.error("set cache error", e);
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            logger.error("set cache error", e);
        }
        return result;
    }

    public long increment(final String key , long delta){
         return redisTemplate.opsForValue().increment(key, delta);
    }

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

5、在功能代码中调用RedisUtil类中的方法,

package com.test.fep.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.test.fep.domain.SysAppLoginToken;
import com.test.fep.mapper.SysAppLoginTokenMapper;
import com.test.fep.redis.RedisUtil;
import com.test.fep.service.AuthService;

import net.sf.json.JSONObject;

@Service("authService")
public class AuthServiceImpl implements AuthService{
    @Autowired
    private SysAppLoginTokenMapper sysAppLoginTokenMapper ;

    @Autowired
    private RedisUtil redisUtil;  //记得注入

    @Override
    public SysAppLoginToken verification(String tokenId) {
        SysAppLoginToken token = null;
        if (redisUtil.exists(tokenId)) {
            token = (SysAppLoginToken) redisUtil.get(tokenId);  //从缓存中查找token
        }else{
            token = sysAppLoginTokenMapper.selectByPrimaryKey(tokenId) ;
            redisUtil.set(tokenId, token);    //将token写入缓存
        }

        return null;
    }
}

好了,到这里就在一个项目中完整地使用了redis。

还需要注意的一点是,所有保存在Redis中的接口都必须要实现Serializable接口

时间: 2024-07-30 20:26:11

Spring下redis的配置的相关文章

Linux下Redis服务器安装配置

说明:操作系统:CentOS1.安装编译工具yum install wget  make gcc gcc-c++ zlib-devel openssl openssl-devel pcre-devel kernel keyutils  patch perl 2.安装tcl组件包(安装Redis需要tcl支持)cd /usr/local/src #进入软件包存放目录wget  http://downloads.sourceforge.net/tcl/tcl8.6.6-src.tar.gztar 

CentOS下Redis服务器安装配置

http://www.centoscn.com/image-text/config/2014/0712/3285.html 1.安装编译工具 yum install wget  make gcc gcc-c++ zlib-devel openssl openssl-devel pcre-devel kernel keyutils  patch perl 2.安装tcl组件包(安装Redis需要tcl支持) 下载:http://downloads.sourceforge.net/tcl/tcl8.

Spring中redis的配置及初级操作

当spring和redis结合时往往都是通过配置bean来解决的首先是配置JedisPoolConfig对象,内容如下: <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxActive" value="100"/> <property name="maxIdle&qu

CentOS 6.6下Redis安装配置记录

转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/120.html?1455855209 在先前的文章中介绍过redis,以下内容为自己在CentOS上安装Redis的记录.供后期在做改进. 1.安装需要的支持环境 在安装Redis之前首要先做的是安装Unix的Tcl工具?,如果不安装的话后期将无法对Redis进行测试.在后期执行make test的时候返回如下错误信息:You need tcl 8.xuyao de5 o

Windows下Redis主从配置出现Writing to master:Unknow error

异常:Sending command to master in replication handshake: -Writing to master: Unknown error: 解决结论: 从数据库的slaveof所写的ip地址要和 主数据库的bind第一个参数相同: 解决过程: 一.当我在一台操作系统为win10的64位电脑上进行redis主从配置时,出现以上错误,死活连接不上,当时配置如下: 1.(master)配置redis.windows.conf (1)bind 127.0.0.1

centos下 redis安装配置及简单测试

1:安装redis(使用的的环境是centos6.7 redis-2.6.14) 将redis-2.6.14.tar.gz文件拷贝到/usr/local/src 目录下 解压文件  tar zxvf redis-2.6.14.tar.gz  进入 redis-2.6.14目录下的src目录  cd src -->编译  make 2:创建redis运行目录(放在/usr/local/redis) makedir /usr/local/redis 拷贝redis-cli redis-server

Linux环境下Redis安装配置步骤[转]

在LInux下安装Redis的步骤如下: 1.首先下载一个Redis安装包,官网下载地址为:https://redis.io/ 2.在Linux下解压redis: tar -zxvf redis-2.8.22.tar.gz 3.解压完成之后,进入到解压的目录里面“”redis-2.8.22”,命令为 cd redis-2.8.22 4.执行 make 命令,如果出现“/bin/sh: cc: command not found ”之类的错误,是因为系统本身没有安装gcc环境.此刻呢我们可以用yu

Spring Data Redis 让 NoSQL 快如闪电(2)

[编者按]本文作者为 Xinyu Liu,文章的第一部分重点概述了 Redis 方方面面的特性.在第二部分,将介绍详细的用例.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 把 Redis 当作数据库的用例 现在我们来看看在服务器端 Java 企业版系统中把 Redis 当作数据库的各种用法吧.无论用例的简繁,Redis 都能帮助用户优化性能.处理能力和延迟,让常规 Java 企业版技术栈望而却步. 1. 全局唯一增量计数器 我们先从一个相对简单的用例开始吧:一个增量计数器,可显示某网

CentOS下Redisserver安装配置

1.CentOS 6.6下Redis安装配置记录 2.CentOS下Redisserver安装配置