(spring redis应用第一章)Spring+Redis的简单应用

这几天,在学习Redis,关于Redis的好处网上有很多的介绍,我不做太多赘述,作为开发人员,首先关心的是怎么用,如何整合到我们的Spring框架中。这里面我简单的将Redis整合到Spring框架,并且做存,取的功能。好了,下面来步骤吧。
第一步:安装Redis数据库。我直接从同事那里要了一个免安装的包。直接在电脑里面启动打开的。怎么装Redis,网上有教程。

第二步:在Spring配置Redis的相关配置,在applicationContext.xml配置

<!-- 6.配置redis服务 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath*:/META-INF/config/redis.properties</value>
            </list>
        </property>
    </bean>
    <import resource="spring-redis.xml" />

第二步:新建一个spring-redis.xml的xml文件。并且在里面做相关配置,其中hostName是你redis所在的IP地址。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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">


    <!--(1)如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true"-->  
   <!--(2)注意新版的(具体从哪个版本开始不清楚,有兴趣可以查一下)JedisPoolConfig的property name,不是maxActive而是maxTotal,而且没有maxWait属性,建议看一下Jedis源码。-->  

    <!-- redis连接池 -->  
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="6"></property>  
        <property name="minEvictableIdleTimeMillis" value="300000"></property>  
        <property name="numTestsPerEvictionRun" value="3"></property>  
        <property name="timeBetweenEvictionRunsMillis" value="60000"></property>  

       <!--  <property name="maxIdle" value="${redis.maxIdle}"></property>  
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property>  
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property>  
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property> -->
    </bean>  

    <!-- redis连接工厂 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">  
        <property name="poolConfig" ref="jedisPoolConfig"></property>  
        <property name="hostName" value="192.168.1.**"></property> 
        <property name="port" value="6379"></property>  
        <property name="timeout" value="15000"></property>  
        <property name="usePool" value="true"></property>  
    </bean>  


    <!-- redis封装的Template API -->
    <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>  
        <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>  
</beans>

第三步:建立RedisTemplateUtil.java

package com.util.base;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class RedisTemplateUtil<T> {

     @Autowired @Qualifier("jedisTemplate")
     public RedisTemplate redisTemplate;

     /**
      * 缓存基本的对象,Integer、String、实体类等
      * @param key 缓存的键值
      * @param value 缓存的值
      * @return  缓存的对象
      */
     public <T> ValueOperations<String,T> setCacheObject(String key,T value)
     {

      ValueOperations<String,T> operation = redisTemplate.opsForValue(); 
      operation.set(key,value);
      return operation;
     }

     /**
      * 获得缓存的基本对象。
      * @param key  缓存键值
      * @param operation
      * @return   缓存键值对应的数据
      */
     public <T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/)
     {
      ValueOperations<String,T> operation = redisTemplate.opsForValue(); 
      return operation.get(key);
     }

     /**
      * 缓存List数据
      * @param key  缓存的键值
      * @param dataList 待缓存的List数据
      * @return   缓存的对象
      */
     public <T> ListOperations<String, T> setCacheList(String key,List<T> dataList)
     {
      ListOperations listOperation = redisTemplate.opsForList();
      if(null != dataList)
      {
       int size = dataList.size();
       for(int i = 0; i < size ; i ++)
       {

        listOperation.rightPush(key,dataList.get(i));
       }
      }

      return listOperation;
     }

     /**
      * 获得缓存的list对象
      * @param key 缓存的键值
      * @return  缓存键值对应的数据
      */
     public <T> List<T> getCacheList(String key)
     {
      List<T> dataList = new ArrayList<T>();
      ListOperations<String,T> listOperation = redisTemplate.opsForList();
      Long size = listOperation.size(key);

      for(int i = 0 ; i < size ; i ++)
      {
       dataList.add((T) listOperation.leftPop(key));
      }

      return dataList;
     }

     /**
      * 缓存Set
      * @param key  缓存键值
      * @param dataSet 缓存的数据
      * @return   缓存数据的对象
      */
     public <T> BoundSetOperations<String,T> setCacheSet(String key,Set<T> dataSet)
     {
      BoundSetOperations<String,T> setOperation = redisTemplate.boundSetOps(key); 
      /*T[] t = (T[]) dataSet.toArray();
        setOperation.add(t);*/


      Iterator<T> it = dataSet.iterator();
      while(it.hasNext())
      {
       setOperation.add(it.next());
      }

      return setOperation;
     }

     /**
      * 获得缓存的set
      * @param key
      * @param operation
      * @return
      */
     public Set<T> getCacheSet(String key/*,BoundSetOperations<String,T> operation*/)
     {
      Set<T> dataSet = new HashSet<T>();
      BoundSetOperations<String,T> operation = redisTemplate.boundSetOps(key); 

      Long size = operation.size();
      for(int i = 0 ; i < size ; i++)
      {
       dataSet.add(operation.pop());
      }
      return dataSet;
     }

     /**
      * 缓存Map
      * @param key
      * @param dataMap
      * @return
      */
     public <T> HashOperations<String,String,T> setCacheMap(String key,Map<String,T> dataMap)
     {

      HashOperations hashOperations = redisTemplate.opsForHash();
      if(null != dataMap)
      {

       for (Map.Entry<String, T> entry : dataMap.entrySet()) { 

        /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */
        hashOperations.put(key,entry.getKey(),entry.getValue());
       } 

      }

      return hashOperations;
     }

     /**
      * 获得缓存的Map
      * @param key
      * @param hashOperation
      * @return
      */
     public <T> Map<String,T> getCacheMap(String key/*,HashOperations<String,String,T> hashOperation*/)
     {
      Map<String, T> map = redisTemplate.opsForHash().entries(key);
      /*Map<String, T> map = hashOperation.entries(key);*/
      return map;
     }



     /**
      * 缓存Map
      * @param key
      * @param dataMap
      * @return
      */
     public <T> HashOperations<String,Integer,T> setCacheIntegerMap(String key,Map<Integer,T> dataMap)
     {
      HashOperations hashOperations = redisTemplate.opsForHash();
      if(null != dataMap)
      {

       for (Map.Entry<Integer, T> entry : dataMap.entrySet()) { 

        /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */
        hashOperations.put(key,entry.getKey(),entry.getValue());
       } 

      }

      return hashOperations;
     }

     /**
      * 获得缓存的Map
      * @param key
      * @param hashOperation
      * @return
      */
     public <T> Map<Integer,T> getCacheIntegerMap(String key/*,HashOperations<String,String,T> hashOperation*/)
     {
      Map<Integer, T> map = redisTemplate.opsForHash().entries(key);
      /*Map<String, T> map = hashOperation.entries(key);*/
      return map;
     }
}

第四步:写一个测试的Demo

package com.controller.user;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.model.User;
import com.util.base.RedisTemplateUtil;

@Controller
@RequestMapping(value = "/user")
@Scope("prototype")
public class RedisTest {

    @Resource
    private RedisTemplateUtil<Object> redisCache;

    //Map的方式
    @RequestMapping(value = "/setmymap")
    public void setmymap(HttpServletRequest request,HttpServletResponse response){
               Map<Integer,String> Map = new HashMap<Integer,String>();
               for(int i = 0 ; i < 20 ; i ++ )
               {
                   Map.put(i, "value"+i);
               }

               redisCache.setCacheIntegerMap("cityMap", Map);
    }

    @RequestMapping(value = "/getmymap")
    public void getmymap(HttpServletRequest request,HttpServletResponse response){
         Map<Integer,String> Map = redisCache.getCacheIntegerMap("cityMap");

         System.out.println("------------city");
         for(int key : Map.keySet())
         {
          System.out.println("key = " + key + ",value=" + Map.get(key));
         }
    }


    //实体类,基本对象
    @RequestMapping(value = "/setmy")
    public void setmy(HttpServletRequest request,HttpServletResponse response){
        User user=new User();//实体类要进行序列化
        user.setName("张三");
        user.setAge("35");
        user.setSex("男");
        redisCache.setCacheObject("user", user);
    }

    @RequestMapping(value = "/getmy")
    public void getmy(HttpServletRequest request,HttpServletResponse response){
        User user=redisCache.getCacheObject("user");
        System.out.println(user.getName()+","+user.getAge());
    }


}

第五步:运行项目。访问url。查看后台控制,先存,后取,下面是控制台打印出来的

张三,35

PS:这是经过我测试且可运行的Demo,有兴趣的同学可以下载下来,自己跑一跑。我的项目里面本身是连接sql server数据库的。如果有同学是其他类型数据库的话,可以在applicationContext.xml文件把数据库连接的地方给注释掉 http://download.csdn.net/download/qq_35515521/10037359

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值