35 SpringBoot與Redis整合
阿新 • • 發佈:2018-12-29
1 引入依賴
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</ artifactId>
</dependency>
2 配置檔案
#配置所有的資料來源
spring:
#Redis
redis:
host: 127.0.0.1
port: 6379
timeout: 5000
jedis:
pool:
#最大連線數
max-active: 8
#最大阻塞等待時間(負數表示沒限制)
max-wait: -1
#最大空閒
max-idle: 8
#最小空閒
min-idle : 0
3 Redis配置
package com.gp6.springboot30.config;
import com.gp6.springboot30.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context. annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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 redis.clients.jedis.JedisPoolConfig;
/**
* Redis配置
*
* @author gp6
* @date 2018-12-28
*/
@Configuration
@PropertySource("classpath:/application.yml")
public class RedisConfig {
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private Integer redisPort;
@Value("${spring.redis.timeout}")
private Integer redisTimeout;
@Value("${spring.redis.jedis.pool.max-active}")
private Integer jedisPoolMaxActive;
@Value("${spring.redis.jedis.pool.max-wait}")
private Integer jedisPoolMaxWait;
@Value("${spring.redis.jedis.pool.min-idle}")
private Integer jedisPoolMinIdle;
@Value("${spring.redis.jedis.pool.max-idle}")
private Integer jedisPoolMaxIdle;
/**
* Jedis連線池配置
*
* @return JedisPoolConfig
*/
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最大空閒數
jedisPoolConfig.setMaxIdle(jedisPoolMaxIdle);
// 連線池的最大資料庫連線數
jedisPoolConfig.setMaxTotal(jedisPoolMaxActive);
// 最大建立連線等待時間
jedisPoolConfig.setMaxWaitMillis(jedisPoolMaxWait);
return jedisPoolConfig;
}
/**
* jedis連線工廠
*
* @param jedisPoolConfig Jedis連線池配置
* @return RedisConnectionFactory
*/
@Bean
public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
// 單臺redis
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
// IP地址
redisStandaloneConfiguration.setHostName(redisHost);
// 埠號
redisStandaloneConfiguration.setPort(redisPort);
// 預設使用的資料庫
redisStandaloneConfiguration.setDatabase(0);
// 密碼
// redisStandaloneConfiguration.setPassword(password);
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
jpcb.poolConfig(jedisPoolConfig);
JedisClientConfiguration jedisClientConfiguration = jpcb.build();
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
}
/**
* @param redisConnectionFactory redis連線工廠
* @return RedisTemplate
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
initRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 設定資料存入 redis 的序列化方式,並開啟事務
*
* @param redisTemplate 模板
* @param factory redis連線工廠
*/
private void initRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
// 開啟事務
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(factory);
}
/**
* @param redisTemplate 模板
* @return RedisUtil
*/
@Bean(name = "redisUtil")
public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
RedisUtil redisUtil = new RedisUtil();
redisUtil.setRedisTemplate(redisTemplate);
return redisUtil;
}
}
4 Redis工具類
package com.gp6.springboot30.utils;
import com.gp6.springboot30.enums.RedisKeyEnum;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* Redis工具類
*
* @author gp6
* @date 2018-12-28
*/
public class RedisUtil {
private RedisTemplate<String, Object> redisTemplate;
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 執行set操作
*
* @param redisKeyEnum Redis中的key列舉
* @param value Redis中的key
* @return boolean
*/
public boolean set(RedisKeyEnum redisKeyEnum, String value) {
try {
redisTemplate.opsForValue().set(redisKeyEnum.getKey(), value);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 執行set操作並且設定生存時間,單位為:秒
*
* @param redisKeyEnum Redis中的key列舉
* @param value Redis中的value
* @param seconds 有效時間
* @return boolean
*/
public boolean set(RedisKeyEnum redisKeyEnum, String value, Integer seconds) {
try {
if (seconds > 0) {
redisTemplate.opsForValue().set(redisKeyEnum.getKey(), value, seconds, TimeUnit.SECONDS);
} else {
set(redisKeyEnum, value);
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* 執行get操作
*
* @param redisKeyEnum Redis中的key列舉
* @return String
*/
public String get(RedisKeyEnum redisKeyEnum) {
return Objects.requireNonNull(redisTemplate.opsForValue().get(redisKeyEnum.getKey())).toString();
}
/**
* 執行刪除操作
*
* @param redisKeyEnum Redis中的key列舉
* @return boolean
*/
public boolean delete(RedisKeyEnum redisKeyEnum) {
return redisTemplate.delete(redisKeyEnum.getKey());
}
/**
* 設定生存時間,單位為:秒
*
* @param redisKeyEnum Redis中的key列舉
* @param seconds 生存時間
* @return boolean
*/
public boolean expire(RedisKeyEnum redisKeyEnum, Integer seconds) {
try {
if (seconds > 0) {
redisTemplate.expire(redisKeyEnum.getKey(), seconds, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
5 Redis的key統一放入
package com.gp6.springboot30.enums;
/**
* Redis key
*
* @author gp6
* @date 2018-12-28
*/
public enum RedisKeyEnum {
/**
* Redis定義key的規則:專案名_模組名_業務名
*/
KEY("KEY", "Redis的Key");
RedisKeyEnum(String key, String desc) {
this.key = key;
this.desc = desc;
}
private String key;
private String desc;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}}
6 測試
package com.gp6.springboot30;
import com.gp6.springboot30.enums.RedisKeyEnum;
import com.gp6.springboot30.utils.RedisUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot30ApplicationTests {
@Autowired
private RedisUtil redisUtil;
@Test
public void contextLoads() {
redisUtil.set(RedisKeyEnum.KEY,"23");
}
}