來吧,兄弟們,前幾天用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章習題
