SpringBoot集成redis【Jedis】
1、pom.xml的引用
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependenc>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
这里的lombok是为了简化实体类的get/set
2、application.properties
spring.redis.host=127.0.0.0
spring.redis.port=6379
spring.redis.password=
#连接超时时间
spring.redis.timeout=0
#连接的库
spring.redis.database=15
#连接池配置
spring.redis.pool.max-total=100
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
3、redis自动注入配置相关的信息
package com.cat.code.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class JedisConf {
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private int redisPort;
@Value("${spring.redis.password}")
private String redisPasswd;
@Value("${spring.redis.database}")
private int redisDb;
@Value("${spring.redis.timeout}")
private int redisTimeout;
@Value("${spring.redis.pool.max-total}")
private int redisMaxTotal;
@Value("${spring.redis.pool.max-wait}")
private int redisMaxWait;
@Value("${spring.redis.pool.max-idle}")
private int redisMaxIdle;
@Value("${spring.redis.pool.min-idle}")
private int redisMinIdle;
@Bean
public JedisPool redisPoolFactory() throws Exception{
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(redisMaxTotal);
jedisPoolConfig.setMaxIdle(redisMaxIdle);
jedisPoolConfig.setMinIdle(redisMinIdle);
jedisPoolConfig.setMaxWaitMillis(redisMaxWait);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setTestOnReturn(true);
// 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
// jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
// 是否启用pool的jmx管理功能, 默认true
jedisPoolConfig.setJmxEnabled(true);
if (redisPasswd != null && redisPasswd.trim().length() == 0) {
redisPasswd = null;
}
JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, redisTimeout, redisPasswd, redisDb);
return jedisPool;
}
}
4、对jedis调用进行简单封装,每次重新获取连接池资源和归还连接池资源
package com.cat.code.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.Serializable;
import java.util.Set;
/**
* @Description: 配置redis连接池
*/
@Component
public class RedisTemplate {
@Autowired
private JedisPool jedisPool;
/**
* key-value存储
* @param key
* @param value
* @return
*/
public boolean set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String res = jedis.set(key, value);
return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return false;
}
/**
* key-value存储设置过期时间
* @param key
* @param value
* @param expire_time
* @return
*/
public boolean set(String key, String value, int expire_time) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String res = jedis.set(key, value, "NX", "EX", expire_time);
return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return false;
}
/**
* key-value存储设置过期时间,当存在替换为新的值
* @param key
* @param value
* @param expire_time
* @return
*/
public boolean setex(String key, String value, int expire_time) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String res = jedis.setex(key, expire_time, value);
return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return false;
}
/**
* 获取key-value 值
* @param key
* @return
*/
public String get(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String res = jedis.get(key);
return res;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* key是否存在
* @param key
* @return
*/
public boolean exist(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Boolean res = jedis.exists(key);
return res;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return false;
}
/**
* list左进队列
* @param key
* @param values
* @return
*/
public Long lpush(String key, String... values) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Long ret = jedis.lpush(key, values);
return ret;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* list 右进队列
* @param key
* @return
*/
public String rpop(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String value = jedis.rpop(key);
return value;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* set key-values存储
* @param key
* @param values
* @return
*/
public Long sadd(String key,String... values){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.sadd(key,values);
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* set key-value获取
* @param key
* @return
*/
public String spop(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.spop(key);
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
*命令将 key 中储存的数字值增一
* @param key
* @return
*/
public Long incr(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.incr(key);
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
5、User实体类,继承Serializable序列化是非必要
package com.cat.code.po;
import lombok.Data;
import java.io.Serializable;
/**
* @Author: lvgang
* @Time: 2019/10/29 16:43
* @Email: lvgang@golaxy.cn
* @Description: todo
*/
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer age;
public User(){}
public User(Long id,String name,Integer age){
this.id = id;
this.name = name;
this.age = age;
}
}
6、调用redis存取,在大部分情况下是OK的,保证资源存取不会出现问题
package com.cat.code;
import com.cat.code.config.RedisTemplate;
import com.cat.code.po.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
/**
* @Author: lvgang
* @Time: 2019/10/29 17:05
* @Email: lvgang@golaxy.cn
* @Description: todo
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServiceSpringDataRedisApplication.class)
public class RedisTest {
private Logger logger = LoggerFactory.getLogger(RedisTest.class);
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ObjectMapper objectMapper = new ObjectMapper();
@Test
public void test1() throws Exception{
String key = "user1";
String json = objectMapper.writeValueAsString(new User(1L,"admin",21));
redisTemplate.set(key,json);
String value = redisTemplate.get(key);
User user = objectMapper.readValue(value,User.class);
logger.info("user:{}",user.toString());
}
@Test
public void test2(){
ExecutorService executorService = Executors.newFixedThreadPool(1000);
IntStream.range(0, 1000).forEach(i->{
executorService.execute(()->{
logger.info("i:{}",i);
redisTemplate.incr("count");//累加
if(i%2==1){
redisTemplate.sadd("set",""+i);//添加
}else {
String value = redisTemplate.spop("set");//取出
logger.info("第i次:{}获取{}",i,value);
}
});
});
}
}
7、写在最后,当我们对redis连接要求不是那么高时,我建议直接使用spring-boot-data-redis
pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
服务直接自动注入使用
@Autowired
private StringRedisTemplate stringRedisTemplate;
还没有评论,来说两句吧...