ssm中使用redis

2019-12-12  本文已影响0人  IT小池

Jedis方式

首先导包:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

1.创建 redis-config.properties

redis.host=127.0.0.1
redis.port=6379
redis.timeout=3000

2.创建 redis.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:redis-config.properties"/>

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"/>

    <!--  scope="singleton" 配置 redis 为单例模式 -->
    <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="1">
            <list>
                <bean class="redis.clients.jedis.JedisShardInfo">
                    <constructor-arg name="host" value="${redis.host}"/>
                    <constructor-arg name="port" value="${redis.port}"/>
                    <constructor-arg name="timeout" value="${redis.timeout}"/>
                </bean>
            </list>
        </constructor-arg>
    </bean>
</beans>

3.创建 RedisPool

package cn.xiaochi.service;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import javax.annotation.Resource;

/**
 *  ===== redis ======
 *  交给spring管理
 */
@Service("redisPool")
@Slf4j
public class RedisPool {

    // 获取 redis.xml 文件中定义的 shardedJedisPool
    @Resource(name = "shardedJedisPool")
    private ShardedJedisPool shardedJedisPool;

    /**
     * 获取 redis实例
     * @return
     */
    public ShardedJedis instance(){
        return shardedJedisPool.getResource();
    }

    /**
     * 关闭 redis
     * @param shardedJedis
     */
    public void safeClose(ShardedJedis shardedJedis){
        try{
            if (shardedJedis != null){
                shardedJedis.close();
            }
        }catch (Exception e){
            log.error("return redis resources exception",e);
        }
    }
}

4.创建基于 redis 的缓存类 CacheUtil

package cn.xiaochi.service;

import cn.xiaochi.beans.CacheKeyConstants;
import cn.xiaochi.util.JsonMapper;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;

import javax.annotation.Resource;

/**
 * redis缓存类
 */
@Service
@Slf4j
public class CacheUtil{

    @Resource(name = "redisPool")
    private RedisPool redisPool;

    /**
     * 存入
     * @param key
     * @param timeoutSeconds
     * @param toSavedValue
     */
    public void saveCache(String key, int timeoutSeconds, String toSavedValue) {
        if (toSavedValue == null) {
            return;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = redisPool.instance();
            shardedJedis.setex(key, timeoutSeconds, toSavedValue);
        } catch (Exception e) {
            log.error("save cache exception, {}", e);
        } finally {
            redisPool.safeClose(shardedJedis);
        }
    }

    /**
     * 取出
     * @param key
     * @return
     */
    public String getCache(String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = redisPool.instance();
            String value = shardedJedis.get(key);
            return value;
        } catch (Exception e) {
            log.error("get cache exception, {}", e);
            return null;
        } finally {
            redisPool.safeClose(shardedJedis);
        }
    }
}

RedisTemplate方式

首先导包:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring‐data‐redis</artifactId>
    <version>2.0.5.RELEASE</version>
</dependency>

建立redis-config.properties

redis.host=127.0.0.1  
redis.port=6379 
redis.pass= 
redis.database=0 
redis.maxIdle=300  // 最大空闲数
redis.maxWait=3000 // 连接时的最大等待毫秒数

创建applicationContext-redis.xml

<context:property‐placeholder location="classpath:redis‐config.properties" />
   <!‐‐ redis 相关配置 ‐‐>
   <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
     <property name="maxIdle" value="${redis.maxIdle}" />  
     <property name="maxWaitMillis" value="${redis.maxWait}" /> 
   </bean> 

   <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host‐name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool‐config‐ref="poolConfig"/> 

   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> 
     <property name="connectionFactory" ref="JedisConnectionFactory" /> 
   </bean>

测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext‐
redis.xml")
public class TestValue {
  @Autowired    
  private RedisTemplate redisTemplate;         
 
  @Test    
  public void test(){
    ############################# 值类型 #############################
    redisTemplate.boundValueOps("name").set("itcast"); 
    String str = (String) redisTemplate.boundValueOps("name").get();// 获取
    redisTemplate.delete("name");// 删除

    ############################# set类型 #############################
    redisTemplate.boundSetOps("namelist1").add("刘备");      
    redisTemplate.boundSetOps("namelist1").add("张飞");   
    Set members = redisTemplate.boundSetOps("nameset").members(); // 获取
    redisTemplate.boundSetOps("nameset").remove("孙权"); // 删除指定项
    redisTemplate.delete("nameset"); // 删除整个set集合

    ############################# List类型 #############################
    // 右压栈:后添加的对象排在后边 [刘备, 张飞]
    redisTemplate.boundListOps("namelist1").rightPush("刘备");      
    redisTemplate.boundListOps("namelist1").rightPush("张飞");   
    // 左压栈 后添加的对象排在前边   [张飞 , 刘备]
    redisTemplate.boundListOps("namelist1").leftPush("刘备");      
    redisTemplate.boundListOps("namelist1").leftPush("张飞");   
    List list = redisTemplate.boundListOps("namelist1").range(0, 10); // 获取
    String s = (String) redisTemplate.boundListOps("namelist1").index(1); // 查询集合某个元素
    // 移除指定个数的值
    redisTemplate.boundListOps("namelist1").remove(1, "张飞"); // 移除集合某个元素

    ############################# Hash类型 #############################
    redisTemplate.boundHashOps("namelist1").put("a","刘备");      
    redisTemplate.boundHashOps("namelist1").put("b","张飞"); 
    // 提取所有的KEY   [a, b]
    Set s = redisTemplate.boundHashOps("namehash").keys();
    // 提取所有的值   [刘备, 张飞]
    List values = redisTemplate.boundHashOps("namehash").values();
    // 根据KEY提取值
    Object object = redisTemplate.boundHashOps("namehash").get("b");
    // 根据KEY移除值
    redisTemplate.boundHashOps("namehash").delete("b");
 
   ############################# ZSet类型 #############################
    // 存值 ,指定分值
    redisTemplate.boundZSetOps("namezset").add("曹操",100000);
    redisTemplate.boundZSetOps("namezset").add("孙权",0);
    redisTemplate.boundZSetOps("namezset").add("刘备",1000);
    // 查询,由低到高
    Set namezset = redisTemplate.boundZSetOps("namezset").range(0,‐1);
    System.out.println(namezset);
    // 查询,由高到低,土豪榜前10
    Set namezset = redisTemplate.boundZSetOps("namezset").reverseRange(0,9);
    System.out.println(namezset);
    // 增加分数
    redisTemplate.boundZSetOps("namezset").incrementScore("孙权",2000);
    // 查询值和分数  TypedTuple是值与分数的封装
    Set<ZSetOperations.TypedTuple> namezset = redisTemplate.boundZSetOps("namezset").reverseRangeWithScores(0, ‐1);
        for(ZSetOperations.TypedTuple typedTuple:namezset){
            System.out.print("姓名:"+typedTuple.getValue());
            System.out.println("金币:"+typedTuple.getScore());
        }

    ############################# 过期时间设置 #############################    
    // 以值类型为例:存值时指定过期时间和时间单位
    redisTemplate.boundValueOps("name").set("itcast");
    redisTemplate.boundValueOps("name").expire(10,TimeUnit.SECONDS);
    // 或者
    redisTemplate.boundValueOps("name").set("itcast",10, TimeUnit.SECONDS);
  }    
}
上一篇下一篇

猜你喜欢

热点阅读