主頁 > 後端開發 > 聽說會redis的帥哥都拿到了月入過萬

聽說會redis的帥哥都拿到了月入過萬

2020-12-06 12:10:53 後端開發

來吧,兄弟們,前幾天用redis干了個大資料事件,今天和大家探討干SpringBoot整合redis,以及redis處理大量資料,不要慫,干就完了,

一、SpringBoot整合redis:

1、首先在pom檔案中匯入redis依賴,用來引入redis的jar包,

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2、在yml檔案中配置redis連接,包括redis主機地址,如果本地也可以不寫,因為redis中的redis.conf組態檔中是127.0.01(也就是本地);埠號port的設定,默認埠號是6379,如果是6379的話,大家也可以不需要在組態檔中進行配置,配置代碼如下所示:

spring:
  redis:
    host: 127.0.0.1
    port: 6379

3、經過匯入redis依賴和配置redis連接,我們到測驗類中測驗下是否成功連接redis非關系型資料庫,大家一定要記得開redis哈,否則這個肯定是連接不上redis的,

	 @Autowired
    //引入官方redisTemplate,這個官方RedisTemplate不太好用,后期我們自己會進行撰寫,在RedisTemplate中允許我們不使用官方的,
    private RedisTemplate redisTemplate;
    @Test
    public void test3(){
        //獲取redis連接
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        //清空資料庫中當前庫的所有資料,類似在redis客戶端中操作FLUSHDB操作
        connection.flushDb();
        
        //這個是操作字串的set方法
        redisTemplate.opsForValue().set("name","ygl");
        //列印獲取的key為name的value值
        System.out.println(redisTemplate.opsForValue().get("name"));

    }

在控制臺成功列印出該key為name的value值,下面給大家展示下在Java中如何像直接在redis客戶端中操作redis資料型別:
在這里插入圖片描述
接下來給大家進去官方RedisTemplate中原始碼分析下,和不用它的原因,
在這里插入圖片描述

二、撰寫自己RedisTemplae

將自己的Template設定成<String,Object>型別,且進行序列化,代碼如下所示,該config大家也可以在企業中使用,

package com.ygl.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

/**
 * @author ygl
 * @description
 * @date 2020/10/10 19:45
 */
@Configuration
public class RedisConfig {
    //撰寫自己的redisTemplate 給該方法起別名,
    @Bean(name = "redisTemplate1")
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}

接下來在自動匯入RrdisTemplate時,千萬要導成自己的,不要再匯入官方Template,
在這里插入圖片描述

三、撰寫redisUntil工具類

剛剛我們每次操作都需要引入RedisTemplate和每次操作redis時都需要類似redisTemplate.opsForValue().set(“name”,“ygl”); 等等,大家肯定不像類似這樣操作,太惡心了吧,年輕人不講武德 ,接下來我給大家來秀一波,寫個工具類,不需要每次都這么惡心操作,工具類代碼如下:

package com.kuang.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
//@Component作用是將RedisUtil注入Spring容器中,交由Spring管理
@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // =============================common============================
    /**
     * 指定快取失效時間
     * @param key  鍵
     * @param time 時間(秒)
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根據key 獲取過期時間
     * @param key 鍵 不能為null
     * @return 時間(秒) 回傳0代表為永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判斷key是否存在
     * @param key 鍵
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 洗掉快取
     * @param key 可以傳一個值 或多個
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }


    // ============================String=============================

    /**
     * 普通快取獲取
     * @param key 鍵
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通快取放入
     * @param key   鍵
     * @param value 值
     * @return true成功 false失敗
     */

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 普通快取放入并設定時間
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒) time要大于0 如果time小于等于0 將設定無限期
     * @return true成功 false 失敗
     */

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 遞增
     * @param key   鍵
     * @param delta 要增加幾(大于0)
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞增因子必須大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }


    /**
     * 遞減
     * @param key   鍵
     * @param delta 要減少幾(小于0)
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞減因子必須大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }


    // ================================Map=================================

    /**
     * HashGet
     * @param key  鍵 不能為null
     * @param item 項 不能為null
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 獲取hashKey對應的所有鍵值
     * @param key 鍵
     * @return 對應的多個鍵值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 鍵
     * @param map 對應多個鍵值
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * HashSet 并設定時間
     * @param key  鍵
     * @param map  對應多個鍵值
     * @param time 時間(秒)
     * @return true成功 false失敗
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 向一張hash表中放入資料,如果不存在將創建
     *
     * @param key   鍵
     * @param item  項
     * @param value 值
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一張hash表中放入資料,如果不存在將創建
     *
     * @param key   鍵
     * @param item  項
     * @param value 值
     * @param time  時間(秒) 注意:如果已存在的hash表有時間,這里將會替換原有的時間
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 洗掉hash表中的值
     *
     * @param key  鍵 不能為null
     * @param item 項 可以使多個 不能為null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }


    /**
     * 判斷hash表中是否有該項的值
     *
     * @param key  鍵 不能為null
     * @param item 項 不能為null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash遞增 如果不存在,就會創建一個 并把新增后的值回傳
     *
     * @param key  鍵
     * @param item 項
     * @param by   要增加幾(大于0)
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }


    /**
     * hash遞減
     *
     * @param key  鍵
     * @param item 項
     * @param by   要減少記(小于0)
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }


    // ============================set=============================

    /**
     * 根據key獲取Set中的所有值
     * @param key 鍵
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根據value從一個set中查詢,是否存在
     *
     * @param key   鍵
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 將資料放入set快取
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 成功個數
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 將set資料放入快取
     *
     * @param key    鍵
     * @param time   時間(秒)
     * @param values 值 可以是多個
     * @return 成功個數
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 獲取set快取的長度
     *
     * @param key 鍵
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 移除值為value的
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 移除的個數
     */

    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // ===============================list=================================

    /**
     * 獲取list快取的內容
     *
     * @param key   鍵
     * @param start 開始
     * @param end   結束 0 到 -1代表所有值
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 獲取list快取的長度
     *
     * @param key 鍵
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 通過索引 獲取list中的值
     *
     * @param key   鍵
     * @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數第二個元素,依次類推
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 將list放入快取
     *
     * @param key   鍵
     * @param value 值
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 將list放入快取
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒)
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 將list放入快取
     *
     * @param key   鍵
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 將list放入快取
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 根據索引修改list中的某條資料
     *
     * @param key   鍵
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 移除N個值為value
     *
     * @param key   鍵
     * @param count 移除多少個
     * @param value 值
     * @return 移除的個數
     */

    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

}

里面大致放了以下這么多的操作,接下來給大家大概總結下:
1、快取失效時間;
2、五大基本資料型別的基本常用操作;
3、判斷該key值是否存在;
4、洗掉快取;
5、快取放入并設定失效時間;
6、遞增,每次增加幾;遞減,每次減幾
7、移除指定value的值等等,
下面來說下如何使用工具類來直接操作redis,代碼如下:

	@Autowired
    private RedisUtil redisUtil;
    @Test
    public void test3(){
        //獲取redis連接
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        //清空資料庫中當前庫的所有資料,類似在redis客戶端中操作FLUSHDB操作
        connection.flushDb();
        
        redisUtil.set("age",18);
        System.out.println(redisUtil.get("age"));

        //這個是操作字串的set方法
        //redisTemplate.opsForValue().set("name","ygl");

        //列印獲取的key為name的value值
        //System.out.println(redisTemplate.opsForValue().get("name"));

    }

自動匯入RedisUtil,然后就可以直接進行操作即可,接下來開始講Oracle資料庫大量資料匯入redis資料庫中且進行模糊查詢方法,
剛剛梳理好資料庫中資料如何更快更快的匯入redis中和獲取,來吧,開干

四:Spring Boot引入Oracle資料庫(為了 獲取大量資料)

首先引入SpingBoot整合myBatis依賴(千萬不要引錯了,否則起不來,這個坑踩過),和Oracle資料庫依賴

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>12.1.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

PS:這個jar包可能下不來,我給大家放到我CSDN資源里了,大家可以下載,地址為:https://download.csdn.net/download/weixin_45150104/13452835
這里我就不和大家寫查詢資料庫中所有內容的controller、service和mapper層了哈,直接寫操作redis的關鍵,算了,還是寫一下吧,直接貼代碼,不具體分析: 大家這部分可以不看,直接跳到第五部分寫好的優化代碼,這里的redis匯入和匯出只是我做測驗分析所使用
總體架構如下圖所示:
在這里插入圖片描述

物體類Test1.class如下圖所示:

package com.kuang.pojo;

import lombok.Data;

/**
 * @author ygl
 * @description
 * @date 2020/12/1 19:54
 */
@Data
public class Test1 {
    public String name;
    public String address;
}

controller層如下圖所示:

package com.kuang.controller;

import com.kuang.service.RedisService;
import com.kuang.service.TestService;
import com.kuang.utils.RandomUtil;
import com.kuang.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author ygl
 * @description
 * @date 2020/12/1 19:15
 */
@RestController
@RequestMapping("/redis")
public class TestController {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private RandomUtil randomUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TestService testService;

    @Autowired
    private RedisService redisService;

    //存入value中,是hash型別,查詢資料庫,匯入到redis中,采用逐條查詢
    @GetMapping("/intoRedis")
    private void intoRedis(){
        testService.start1();
    }
    //將值存入到key中,是set型別,匯入到redis中,采用逐條查詢
    @GetMapping("/intoRedis2")
    private void intoRedis2(){
        testService.start2();
    }

    @GetMapping("/test")
    private void test(){
        long l = redisUtil.sSet("key01", "1", "2", "3");
        System.out.println("長度:"+l);
        redisUtil.sGet("key01");
        System.out.println();
        
    }

    @GetMapping("/likeByOne")
    private List test1(String pattern){
        Date date1 = new Date();
        //模糊查詢
//        Set keys = redisTemplate.keys("*" + pattern + "*");

        //通過外層key拿到下面的物件,外層key一般都是已知的
        Map<String, String> entries = redisTemplate.opsForHash().entries("key01");
        List<String> list = new ArrayList<>();
        List<String> listNew = new ArrayList<>();
        //遍歷快取物件
        for (String value : entries.keySet()) {
            //如果value是物件直接強轉物件即可
            String o = (String) entries.get(value);
            //字串在快取中取出來有的時候會多出一對雙引號,可以debug看一下,把引號去掉
            o = o.replace("\"", "");
            //用假設前端的value和物件下的value相比較,相同則添加到list集合中,然后回傳
            if (o.matches(".*"+pattern+".*")){
                System.out.println("值:"+o);
//                String key01 =(String) redisUtil.hget("key01", o);
//                System.out.println("key01:"+key01);
                listNew.add(o);
            }
        }
        System.out.println("總條數:"+list.size());
        Date date2 = new Date();
        System.out.println("結束時間:"+date1);
        System.out.println("結束時間:"+date2);
        return listNew;
    }
    //將值存入到key中進行查詢
    @GetMapping("/likeByOne2")
    private Set test2(String pattern){
        Date date1 = new Date();
        //模糊查詢
        Set keys = redisTemplate.keys("*" + pattern + "*");
        Date date2 = new Date();
        System.out.println("結束時間:"+date1);
        System.out.println("結束時間:"+date2);
        return keys;
    }
}

這里在查詢到資料庫,取到大量資料(47萬8千多條),然后進行插入redis和從redis中模糊取得資料,進行了多種對比,我先把這三層寫完,最后做詳細描述,
TestService介面:

package com.kuang.service;

import com.kuang.pojo.Test1;

import java.util.List;

/**
 * @author ygl
 * @description
 * @date 2020/12/1 19:51
 */
public interface TestService {
    List<Test1> findAll();
    void start1();
    void start2();
}

TestService實作類:

package com.kuang.service.impl;

import com.kuang.mapper.TestMapper;
import com.kuang.pojo.Test1;
import com.kuang.service.TestService;
import com.kuang.utils.RandomUtil;
import com.kuang.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author ygl
 * @description
 * @date 2020/12/1 19:56
 */
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private TestMapper testMapper;

    @Autowired
    private TestService testService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RandomUtil randomUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<Test1> findAll() {
        return testMapper.findAll();

    }

    @Override
    //定時任務
    @Scheduled(cron = "0 8 0 1-31 * ? ")
    public void start1() {
        System.out.println("開始、、、、");
        Date date1 = new Date();
        List<Test1> all = testService.findAll();
        //獲取redis連接  且將當前庫中所有key value洗掉
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//        connection.flushDb();
//        String str= JSON.toJSONString(all);
//        redisUtil.hset("key01","10001",str);

        System.out.println("大小:"+all.size());
        for (int i=0;i<all.size();i++){
            Test1 test = all.get(i);
            String s = test.toString();
            String itemID = randomUtil.getItemID(10);
            redisUtil.hset("key01",itemID,s);
        }
        Date date2 = new Date();
        System.out.println("結束時間:"+date1);
        System.out.println("結束時間:"+date2);
    }

    @Override
    //定時任務
    @Scheduled(cron = "0 8 1 1-31 * ? ")
    public void start2() {
        Date date1 = new Date();
        List<Test1> all = testService.findAll();
        //獲取redis連接  且將當前庫中所有key value洗掉
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        //connection.flushDb();

        System.out.println("大小:"+all.size());
        for (int i=0;i<all.size();i++){
            Test1 test = all.get(i);
            String s = test.toString();
            redisUtil.set(s,"你好");
        }
        Date date2 = new Date();
        System.out.println("結束時間:"+date1);
        System.out.println("結束時間:"+date2);
    }
}

TestMapper代碼如下圖所示:

package com.kuang.mapper;

import com.kuang.pojo.Test1;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author ygl
 * @description
 * @date 2020/12/1 19:57
 */
@Mapper
public interface TestMapper {
    List<Test1> findAll();
}

TestMapper.xml檔案如下圖所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.TestMapper">
    <select id="findAll" resultType="com.kuang.pojo.Test1">
        select NAME,ADDRESS
        from TBL_SZ_KJJG_SHOW
    </select>
</mapper>

組態檔如下圖所示:

#reids的IP地址
#spring.redis.host=127.0.0.1
#redis埠號
#spring.redis.port=6379

spring:
  redis:
    host: 127.0.0.1
    port: 6379
  application:
    name: user-service
  datasource:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@192.168.31.203:1521:orcl203  寫自己的
    username: root  寫自己的
    password: 123456  寫自己的
    max-idle: 10
    max-wait: 10000
    min-idle: 5
    initial-size: 5
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB`在這里插入代碼片`

mybatis:
  type-aliases-package: com.kuang.pojo
  mapper-locations: classpath:mapper/*.xml

接下來我給大家分析下上面我所寫的 垃圾代碼 ,當時為了和各種情況做對比使用:
1、首先我為了簡便,直接存放的資料型別為String型別,因為redisTemplate中有自帶的模糊查詢(Set keys = redisTemplate.keys("*" + pattern + "*");),這里我就直接將查詢出來的值放到key中,效率賊快,在迷糊查詢時,當查詢出來一萬多條時,直接秒出,效率真的是高,但是這不符合常規啊,哪有把資料放在redis中的key里面的,嚇唬鬧,換吧,所有有了第二種,
PS: 插入的時候,采用的47萬多條資料逐條插入,來個for回圈,效率特別低,大概用時122秒左右(真實實驗資料支撐,包括查詢資料庫時間),
2、第二種放到value中,采用的hash結構,key值就設定一個,item我設定成隨機生成的十位字符,value放存放的從資料庫中查出內容,大量資料放redis中和第一種一樣,這個插入也是采用逐條插入,效率特別特別低,這個47萬多條插入,用了121秒左右(包括查詢資料庫時間),這個我等會給大家分析個牛逼方法,
3、這個在模糊查詢中,采用的是先取出所有的key值,然后把key值放到list集合中,再遍歷所有的key值,逐個取出value值,然后和從前端的值去對比,才用方法是(value.matches(". * “+str+”. *")),如何滿足就將value放到list集合中然后回傳,這種查詢出來一萬多條符合條件的資料用時9秒左右,效率也是比較低,

五、放大招,不瞞各位,前面全是垃圾,開始牛逼的批量匯入redis和從redis中匯出資料:

開始扔干貨,接著哈,剛才上面分享的那種逐潭訓入和匯出資料庫真的效率太慢了,無法用語言來形容,昨天晚上就和經常使用redis的同學商量如何批量匯入資料和匯出資料,他給出的建議是采用管道流(Pipelined),RedisTemplate中有redisTemplate.executePipelined(); 進行管道操作
批量插入實作代碼如下圖所示:

@Test
    public void testPipellined(){
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushDb();
        System.out.println("開始查詢資料庫");
        List<Test1> all = testService.findAll();
        System.out.println("大小:"+all.size());
        System.out.println("開始匯入redis");
        long l = System.currentTimeMillis();
//        for (int i = 0;i<all.size();i++){
//            Test1 test1 = all.get(i);
//            String s = JSON.toJSONString(test1);
//            redisUtil.set(("iii"+i),s);
//
//        }
        redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                for (int i = 0; i < all.size(); i++) {
                    Test1 test1 = all.get(i);
                    String s = JSON.toJSONString(test1);
                    connection.set(("pipel:" + i).getBytes(),s.getBytes() );
                }

                return null;
            }
        });
        long l1 = System.currentTimeMillis();
        System.out.println("結束:"+(l1-l));
    }

這次47萬多條資料用時9272毫秒毫秒哈,為了做對比,我又寫了個對照組,又寫了個普通的for回圈逐條插入,這個逐條插入資料用時57766毫秒左右(真實資料支撐哈)
批量查詢實作代碼如下圖所示:

	@Test
    public void selectPipellined(){
        System.out.println("開始查詢");
        long l = System.currentTimeMillis();
        List<String> keys = new ArrayList<>();
        for (int i = 0; i < 478385; i++) {
            keys.add(("pipel:" + i));
            System.out.println("第一次:"+i);
        }
        redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                for (String key : keys) {
                    connection.get(key.getBytes());
                    System.out.println("第二次:"+key);
                }
                System.out.println("大小:"+redisTemplate.keys("*").size());
                return null;
            }
        });
        long l1 = System.currentTimeMillis();

        System.out.println("結束:"+(l1-l));
    }

這里的第一個for回圈是為了模擬前端傳來的key集合,
好了以上就是批量匯入匯出,速度賊快,希望能夠幫助大家,

六、redis快取和資料庫一致性問題

說起redis,那么和資料庫一致性問題就沒法不談啊,redis的軟肋啊,接下來我和大家分析分析這方面的解決方法和存在的問題:
1、更新:先更新資料庫,然后洗掉快取
讀取:先進快取中進行讀取,如果不存在進進資料庫中查詢,資料庫中查詢到的話然后再將資料放到redis快取中,
問題:當資料庫已經更新,快取中還沒有洗掉,這是過來讀取的執行緒,先直接從快取中讀取到,然后就直接回傳,這肯定不行,
2、更新:先洗掉快取,后更新資料庫,
讀取:先進快取中進行讀取,如果不存在進進資料庫中查詢,資料庫中查詢到的話然后再將資料放到redis快取中,
問題:快取已經洗掉,資料庫還沒有更新,這個時候來讀取資料,快取中找不到,然后進資料庫中拿取資料,拿到的是未更新的資料,這肯定是臟資料啊,所以這個也不行,
面對這兩種問題,我們可以在寫的時候來進行視情況而定
第一種并發量不高:關于寫的時候,先寫資料庫,然后寫redis.
第二種并發量比較高:關于寫的時候,先寫redis,然后直接回傳,定期或者特定動作的時候將redis中的資料更新至資料庫中,可以多次更新,一次保存,
第三種:可以寫個定時任務全部洗掉redis中資料,然后將資料庫中資料重新寫入redis中,
第五種:這個成本可能比較高些,redis和資料庫分離,也就是根本不要資料庫,所有資料放到快取redis中,這個方法還是昨天晚上和同學探討出來的,嘻嘻,

七、補充: json中的json.parseObject()方法和json.tojsonString()方法,

首先引入阿里巴巴的fastjson依賴:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
    <scope>compile</scope>
</dependency>

然后就可以直接使用,
JSON.parseObject,是將Json字串轉化為相應的物件;JSON.toJSONString則是將物件轉化為Json字串,
目前先到此結束吧,后期有新的知識點再進行更新,那些講的不太明白的小伙伴可以在下面留言討論,歡迎轉發點贊和評論,
讓自己變的更強,唯有不斷努力,加油,沖啊

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/230717.html

標籤:java

上一篇:Spring 注解面面通 之 @MatrixVariable引數系結原始碼決議

下一篇:java網路編程1、2章習題

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more