spring整合redis

《myeclipse + tomcat8.0 + jdk1.8.0 + ssm + maven》
一.
添加jar包

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.6.2.RELEASE</version>
		</dependency>
		<!-- redis客户端jar -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>

二.
编写配置文件
整合文件位置图
这里我就偷了个懒,把redis.xml 配置在了spring-mybatis.xml里面 当然也可以创建一个spring-redis.xml 文件来编写
单独创建的话就需要在web.xml文件中进行引入
先来看看jedis.prorerties文件的编写:

# ip地址
redis.host=*******
# 端口
redis.port=****
# 密码
redis.auth=****
# 最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。  
redis.maxIdle=300  
# 连接池的最大数据库连接数。设为0表示无限制  
redis.maxActive=600  
# 当连接池资源耗尽时,调用者最大阻塞时间,超时将抛出异常.单位:毫秒,默认:-1,表示永不超时.
redis.maxWaitMillis=1000  
# 在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;  
redis.testOnBorrow=true 

redis配置xml文件编写实则和配置mybatis的xml文件编写差不多如下:

 	<!-- 引入配置文件  注:context:property-placeholder 标签如果引入多个必须加上ignore-unresolvable="true" 否则会报错  -->
	<context:property-placeholder location="classpath:/config/jedis.properties" ignore-unresolvable="true"/>
	
	<!-- jedis 连接池配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    	<!-- #连接池的最大数据库连接数。设为0表示无限制 -->
        <property name="maxTotal" value="${redis.maxActive}" />
        <!-- #最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。 -->
        <property name="maxIdle" value="${redis.maxIdle}" />
        <!-- #在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的; -->
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
		<!-- #当连接池资源耗尽时,调用者最大阻塞时间,超时将抛出异常.单位:毫秒,默认:-1,表示永不超时. -->
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
    </bean>
    
    <!-- redis连接工厂 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig"/>
        <property name="hostName" value="${redis.host}"/>
        <property name="port" value="${redis.port}"/>
        <property name="password" value="${redis.auth}"/>
        <property name="timeout" value="${redis.timeout}"></property>
        <!-- usePool:是否使用连接池 -->
        <property name="usePool" value="true"/>
    </bean>
    <!-- redis操作模板,这里采用尽量面向对象的模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <!-- 指定redis中key-value的序列化方式(此处省略) -->
    </bean>
    
    <bean id="redisUtil" class="com.co.util.RedisUtil">
        <property name="redisTemplate" ref="redisTemplate"/>
    </bean>

以上就配置得差不多了,附上简单RedisUtil类

package com.co.util;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * Redis工具类
 */
public class RedisUtil {
	@Autowired
    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) {
            e.printStackTrace();
        }
        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) {
            e.printStackTrace();
        }
        return result;
    }

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

接下来写个测试类简单测试一下:

package com.co.util;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:config/spring-mybatis.xml")
@SuppressWarnings("all") // 强制祛除警告
public class redisTest {

	@Autowired
	private  RedisUtil redisUtil;
	
	@Test
	public void test1 (){
		redisUtil.set("name", "123");
		Object object = redisUtil.get("name");
		System.out.println(object.toString());
	}
}

OK结果:
在这里插入图片描述
简单的使用,redis的缓存的数据类型有几种可以在util里编写拓展,后期还会继续学习跟新redis集群的使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值