spring-boot集成mybatis,用redis做緩存


網上有很多例子了,執行源碼起碼有3個,都是各種各樣的小問題。

現在做了個小demo,實現spring-boot 用redis做緩存的實例,簡單記錄下思路,分享下源碼。

緩存的實現,分擔了數據庫的壓力,在CRUD中

C:需要同時更新redis和mysql中的數據。

R:看redis中 有無數據,有,就從緩存中取,沒有就從數據庫中取,同時更新緩存。

U:刪除redis中的數據,並update數據庫。

D:刪除redis和mysql的數據。

 

1、基本步驟

  (1)redis安裝  http://download.csdn.net/download/xsx531588644/9565831

  (2)配置pom.xml

  (3)添加工具類

  (4)添加項目啟動掃描類

  (5)修改controller

2、實現

  (1)安裝redis

                 有一個redis圖形管理工具很好用RedisManager,可以一起裝上。

      引入操作redis的客戶端包jedis,見下方的總結。

  (2)配置pom.xml

    添加代碼

  

<!-- 熱部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        
        <!-- redis cache related.....start -->  
        <dependency>  
            <groupId>org.springframework.data</groupId>  
            <artifactId>spring-data-redis</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>redis.clients</groupId>  
            <artifactId>jedis</artifactId>  
        </dependency>

完整pom.xml代碼

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sun</groupId>
  <artifactId>spring-boot-test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
    
    <dependencies>
          <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        
        
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
        
        <!-- 熱部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        
        <!-- redis cache related.....start -->  
        <dependency>  
            <groupId>org.springframework.data</groupId>  
            <artifactId>spring-data-redis</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>redis.clients</groupId>  
            <artifactId>jedis</artifactId>  
        </dependency>
    </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
View Code

    (3)添加redis工具類

    

package com.sun.beans;

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 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.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisCacheUtil<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        緩存鍵值對應的數據
     */
    @SuppressWarnings({ "unchecked", "hiding" })
    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            緩存數據的對象
     */
    @SuppressWarnings({ "unchecked", "hiding" })
    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;
    }
}
View Code

 

    (4)添加redis監聽,項目啟動時自動緩存數據

package com.sun.beans;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.sun.dao.UserMapper;
import com.sun.model.User;

/*
 * 監聽器,用於項目啟動的時候初始化信息
 */
@Service
public class StartAddCacheListener implements ApplicationListener<ContextRefreshedEvent>
{
    @Resource
    private RedisCacheUtil<Object> redisCache;
    

    @Resource
    private UserMapper userMapper;
    
    @Override
    public void onApplicationEvent(ContextRefreshedEvent  event) 
    { 
        //spring 啟動的時候緩存user等信息
        if(event.getApplicationContext().getParent() == null)
        {
            System.out.println("\n\n\n_________\n\n緩存數據 \n\n ________\n\n\n\n");
            List<User> userList = userMapper.selectAll();
            
            Map<Integer,User> userMap = new HashMap<Integer,User>();
            
            int cityListSize = userList.size();
            
            for(int i = 0 ; i < cityListSize ; i ++ )
            {
                userMap.put(userList.get(i).getId(), userList.get(i));
            }
            
            
            redisCache.setCacheIntegerMap("userMap", userMap);
        }
    }
    
}
View Code

    

    (5)修改TestController添加如下代碼:

    

@Autowired
    private RedisCacheUtil<User> redisCache;

    @RequestMapping("/testGetCache")
    public String testGetCache()
    {

        System.out.println("------------user");
        Map<Integer,User> userMap = redisCache.getCacheIntegerMap("userMap");
        for(int key : userMap.keySet())
        {
            System.out.println("key = " + key + ",value=" + userMap.get(key));
        }
        return userMap.toString();
    }

注意:這里要序列化User實體類,也就是public class User  implements Serializable{

 

 

 

3、總結

  (1)redis是用客戶端jedis操作的。所以jedis包我都是手動添加,工程根節點building path-》

  

這樣添加的。如果你有更好的方式,請留言。版本號是2.9.0。

而且做這個redis的時候我發現版本號的問題十分討厭,在網上下了redis的windows安裝版本,但是安裝了卻沒有jar包,

所以又在網上下了redis的3.2.100版本,但是卻在工程里不知道版本號怎么寫,后來使用的例子代碼多了,發現maven管理的jar包中最高有1.8的,

就一直這么寫了,有大神可以分析下為什么嗎?

 

(2)redis的Windows版是自啟動的,這樣我改了redis-server.conf密碼后,在項目中仍然設置了密碼,提示auth錯誤。

注釋掉項目中的密碼設置就可以了。

 

(3)在applicationContext.xml中設置redis的配置文件,查資料說2種方式都可以,但是發現一種是報錯的,只有

<context:property-placeholder location="classpath*:redis.properties" ignore-unresolvable="true" /> 這樣可行,不知道為什么?有大神解答么?

(4)添加了幾個配置文件applicationContext.xml和redis.properties和spring-redis.xml。

需要注意在啟動類中的掃描代碼:

@ImportResource(locations={"classpath:applicationContext.xml"})

 

最后給一下源碼https://github.com/sunfengjiajia/spring-boot-test


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM