Springg整合Redis详细步骤+实例

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

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


    
        
        
        
            
                classpath*:/META-INF/config/redis.properties
            
        
    
    

第二步:新建一个spring-redis.xml的xml文件。并且在里面做相关配置,其中hostName是你redis所在的IP地址。redis默认是没有密码的





      
     

      
      
          
          
          
          

       
      

    
      
          
         
          
          
          
      


    
      
          
          
              
          
          
              
          
      

第三步:建立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 {

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

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

      ValueOperations operation = redisTemplate.opsForValue(); 
      operation.set(key,value);
      return operation;
     }

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

     /**
      * 缓存List数据
      * @param key  缓存的键值
      * @param dataList 待缓存的List数据
      * @return   缓存的对象
      */
     public  ListOperations setCacheList(String key,List 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  List getCacheList(String key)
     {
      List dataList = new ArrayList();
      ListOperations 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  BoundSetOperations setCacheSet(String key,Set dataSet)
     {
      BoundSetOperations setOperation = redisTemplate.boundSetOps(key); 
      /*T[] t = (T[]) dataSet.toArray();
        setOperation.add(t);*/


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

      return setOperation;
     }

     /**
      * 获得缓存的set
      * @param key
      * @param operation
      * @return
      */
     public Set getCacheSet(String key/*,BoundSetOperations operation*/)
     {
      Set dataSet = new HashSet();
      BoundSetOperations 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  HashOperations setCacheMap(String key,Map dataMap)
     {

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

       for (Map.Entry 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  Map getCacheMap(String key/*,HashOperations hashOperation*/)
     {
      Map map = redisTemplate.opsForHash().entries(key);
      /*Map map = hashOperation.entries(key);*/
      return map;
     }



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

       for (Map.Entry 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  Map getCacheIntegerMap(String key/*,HashOperations hashOperation*/)
     {
      Map map = redisTemplate.opsForHash().entries(key);
      /*Map 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 redisCache;

    //Map的方式
    @RequestMapping(value = "/setmymap")
    public void setmymap(HttpServletRequest request,HttpServletResponse response){
               Map Map = new HashMap();
               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 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
  • 1

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

--------------------- 本文来自 回首凡尘五百年 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/qq_35515521/article/details/78327242?utm_source=copy

你可能感兴趣的:(Redis,Spring,架构之路)