1. 程式人生 > 實用技巧 >Reids整合到Spring的方式 以及使用方法

Reids整合到Spring的方式 以及使用方法

新增相應的依賴到Springboot中 後配置yml檔案

# redis配置,預設沒有密碼
redis:
host: 127.0.0.1
port: 6379
password:
jedis:
pool:
min-idle: 8
max-idle: 500
max-active: 2000
max-wait: 10000
timeout: 0
配置結束後
package com.febs.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.Serializable;
import java.nio.charset.Charset;
import java.time.Duration;

@Configuration
//通過@Configuration標籤去注入到spring的啟動中
public class RedisConfig extends CachingConfigurerSupport {
//繼承CachingConfigurerSupport(快取配置器支援)

//讀取yml配置檔案中的host
@Value("${spring.redis.host}")
private String host;

//讀取yml配置檔案中的埠port
@Value("${spring.redis.port}")
private int port;

//讀取yml配置檔案中的password,預設是沒有密碼
@Value("${spring.redis.password}")
private String password;

//讀取連線超時時間
@Value("${spring.redis.timeout}")
private int timeout;

//配置jedis執行緒池中的最大連線數量
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;

//配置jedis執行緒池中的最長等待時間
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;

//將redis的預設執行緒池設定為0
@Value("${spring.redis.database:0}")
private int database;


/**
* Jedis執行緒池配置,通過Bean標籤注入
* @return
*/
@Bean
public JedisPool redisPoolFactory() {
//新建一個執行緒池
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//將執行緒池中的最大連線數存入
jedisPoolConfig.setMaxIdle(maxIdle);
//配置執行緒池中的最長等待時間
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
//如果密碼不為空返回有連線密碼狀態的執行緒池
if (StringUtils.isNotBlank(password)) {
return new JedisPool(jedisPoolConfig, host, port, timeout, password, database);
} else {
return new JedisPool(jedisPoolConfig, host, port, timeout, null, database);
}
}

/**
* Jedis連線工廠配置,通過Bean標籤注入
* @return
*/
@Bean
JedisConnectionFactory jedisConnectionFactory() {
//新建一個Redis的獨立配置中心
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
//存入密碼 埠 密碼 以及資料庫
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
redisStandaloneConfiguration.setDatabase(database);
//Jedis配置生成器
JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
jedisClientConfiguration.connectTimeout(Duration.ofMillis(timeout));
//使用剛剛注入的連線池
jedisClientConfiguration.usePooling();
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration.build());
}

/**
* 將Jedis的資料進行序列化,方便傳輸
* @param redisConnectionFactory
* @return
*/
@Bean(name = "redisTemplate")
@SuppressWarnings({"unchecked", "rawtypes"})
//這個標籤的意思是,不使用預設的(redisTemplate)
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
//建立一個RedisTemplate(Redis資料模板,如果不進行序列化讀取資料可能會亂碼)
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//將key跟value進行序列化
//使用 fastjson 序列化
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// value 值的序列化採用 fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// key 的序列化採用 StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
//將序列化好的配置工廠返回給spring
template.setConnectionFactory(redisConnectionFactory);
return template;
}

//快取管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//建立一個redis的快取管理器,從redis的連線工廠中設定快取管理器
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
.RedisCacheManagerBuilder
.fromConnectionFactory(redisConnectionFactory);
return builder.build();
}

@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) {
//將Redis的key進行一個序列化模板的設定
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}

@Bean
public KeyGenerator wiselyKeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
};
}

@Bean
public RedisTemplate<String, Serializable> limitRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
//將其中配置一個極限redis模板直接進行序列化直接呼叫json的序列化模板 方法的過載應該是
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}

class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
//配置redis的一個序列化器
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;

FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}

@Override
public byte[] serialize(T t) {
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}

@Override
public T deserialize(byte[] bytes) {
//redis的反序列化
if (bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
}
以上的配置結束後redis就已經注入到spring中了

接下來就是
redis的一個簡單工具類
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.febs.common.domain.RedisInfo;

public interface RedisService {
String set(String key,String value,Long milliseconds);

/**
* 獲取 redis 的詳細資訊
*
* @return List
*/
List<RedisInfo> getRedisInfo();

/**
* 獲取 redis key 數量
*
* @return Map
*/
Map<String, Object> getKeysSize();

/**
* 獲取 redis 記憶體資訊
*
* @return Map
*/
Map<String, Object> getMemoryInfo();

/**
* 獲取 key
* @param pattern 正則
* @return Set
*/
Set<String> getKeys(String pattern);

/**
* get命令
*
* @param key key
* @return String
*/
String get(String key);

/**
* set命令
*
* @param key key
* @param value value
* @return String
*/
String set(String key, String value);

/**
* del命令
*
* @param key key
* @return Long
*/
Long del(String... key);

/**
* exists命令
*
* @param key key
* @return Boolean
*/
Boolean exists(String key);

/**
* pttl命令
*
* @param key key
* @return Long
*/
Long pttl(String key);

/**
* pexpire命令
*
* @param key key
* @param milliscends 毫秒
* @return Long
*/
Long pexpire(String key, Long milliscends);
}
===============================================================>>>>>>>>>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.febs.common.domain.RedisInfo;
import com.febs.common.service.RedisService;

import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;
import java.util.function.Function;

/**
* Redis 工具類,只封裝了幾個常用的 redis 命令,
* 可根據實際需要按類似的方式擴充套件即可。
*
*/
@Service("redisService")
@SuppressWarnings("unchecked")
public class RedisServiceImpl implements RedisService {

private Logger log = LoggerFactory.getLogger(this.getClass());

@Autowired
JedisPool jedisPool;


/**
* 處理jedis請求
*
* @param f 處理邏輯,通過lambda行為引數化
* @return 處理結果
*/
private Object excuteByJedis(Function<Jedis, Object> f) {
try (Jedis jedis = jedisPool.getResource()) {
return f.apply(jedis);
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}

@Override
public List<RedisInfo> getRedisInfo() {
String info = (String) this.excuteByJedis(
j -> {
Client client = j.getClient();
client.info();
return client.getBulkReply();
}
);
List<RedisInfo> infoList = new ArrayList<>();
String[] strs = Objects.requireNonNull(info).split("\n");
RedisInfo redisInfo;
if (strs.length > 0) {
for (String str1 : strs) {
redisInfo = new RedisInfo();
String[] str = str1.split(":");
if (str.length > 1) {
String key = str[0];
String value = str[1];
redisInfo.setKey(key);
redisInfo.setValue(value);
infoList.add(redisInfo);
}
}
}
return infoList;
}

@Override
public Map<String, Object> getKeysSize() {
long dbSize = (long) this.excuteByJedis(
j -> {
Client client = j.getClient();
client.dbSize();
return client.getIntegerReply();
}
);
Map<String, Object> map = new HashMap<>();
map.put("create_time", System.currentTimeMillis());
map.put("dbSize", dbSize);
return map;
}

@Override
public Map<String, Object> getMemoryInfo() {
String info = (String) this.excuteByJedis(
j -> {
Client client = j.getClient();
client.info();
return client.getBulkReply();
}
);
String[] strs = Objects.requireNonNull(info).split("\n");
Map<String, Object> map = null;
for (String s : strs) {
String[] detail = s.split(":");
if ("used_memory".equals(detail[0])) {
map = new HashMap<>();
map.put("used_memory", detail[1].substring(0, detail[1].length() - 1));
map.put("create_time", System.currentTimeMillis());
break;
}
}
return map;
}

@Override
public Set<String> getKeys(String pattern) {
return (Set<String>) this.excuteByJedis(j -> j.keys(pattern));
}

@Override
public String get(String key) {
return (String) this.excuteByJedis(j -> j.get(key));
}

@Override
public String set(String key, String value) {
return (String) this.excuteByJedis(j -> j.set(key, value));
}

@Override
public Long del(String... key) {
return (Long) this.excuteByJedis(j -> j.del(key));
}

@Override
public Boolean exists(String key) {
return (Boolean) this.excuteByJedis(j -> j.exists(key));
}

@Override
public Long pttl(String key) {
return (Long) this.excuteByJedis(j -> j.pttl(key));
}

@Override
public Long pexpire(String key, Long milliseconds) {
return (Long) this.excuteByJedis(j -> j.pexpire(key, milliseconds));
}

@Override
public String set(String key, String value, Long milliseconds) {
return (String) this.excuteByJedis(j -> j.psetex(key, milliseconds, value) );
}
}