在springboot1.5.x版本中,springboot默认是使用jedis来操作redis的,但是在springboot2.x版本,默认是使用lettuce来操作数据库,所以配置有些差别。具体的使用参照下面的步骤:
pom配置如下:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE
com.jack
springboot2-redis
0.0.1-SNAPSHOT
springboot2-redis
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-redis
slf4j-api
org.slf4j
redis.clients
jedis
io.lettuce
lettuce-core
redis.clients
jedis
2.10.2
org.apache.commons
commons-pool2
2.6.2
com.alibaba
fastjson
1.2.58
org.projectlombok
lombok
1.18.8
provided
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
获取redis配置的节点信息
package com.jack.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* Created By Jack on 2019/7/10
*
* @author Jack
* @date 2019/7/10 19:48
* @Description:
*/
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterProperties {
/**
* cluster nodes,redis节点数组
*/
private List nodes=new ArrayList<>();
public List getNodes() {
return nodes;
}
public void setNodes(List nodes) {
this.nodes = nodes;
}
}
jedis的配置类信息:
package com.jack.config;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Created By Jack on 2019/7/10
*
* @author Jack
* @date 2019/7/10 19:49
* @Description:
*/
@Configuration
@ConditionalOnClass(RedisClusterConfig.class)
@EnableConfigurationProperties(RedisClusterProperties.class)
public class RedisClusterConfig {
/**
* 获取redis的集群的配置ip+端口
*/
@Resource
private RedisClusterProperties redisClusterProperties;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisCluster redisCluster() {
Set nodes = new HashSet<>();
for (String node : redisClusterProperties.getNodes()) {
String[] parts = StringUtils.split(node, ":");
Assert.state(parts.length == 2, "redis node shoule be defined as 'host:port', not '" + Arrays.toString(parts) + "'");
nodes.add(new HostAndPort(parts[0], Integer.valueOf(parts[1])));
}
//没有配置连接池使用默认的连接池
//return new JedisCluster(nodes);
//创建集群对象
JedisCluster jedisCluster = null;
if (!StringUtils.isEmpty(password)) {
jedisCluster = new JedisCluster(nodes, 6000, 1500, 3, password, jedisPoolConfig());
} else {
jedisCluster = new JedisCluster(nodes,6000,jedisPoolConfig());
}
return jedisCluster;
}
/**
* jedis的连接池
* @return
*/
@Bean
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
jedisPoolConfig.setMinIdle(5);
jedisPoolConfig.setMaxIdle(20);
jedisPoolConfig.setMaxWaitMillis(24000);
return jedisPoolConfig;
}
}
redis的模板配置:
package com.jack.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.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
/**
* Created By Jack on 2019/7/10
*
* @author Jack
* @date 2019/7/10 19:30
* @Description:
*/
@Configuration
public class JedisRedisConfig {
/**
* redis模板配置
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
//设置序列化,使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper =new ObjectMapper();
//指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
//redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
server:
port: 9090
spring:
redis:
password: ""
cluster:
nodes:
- x.x.x.x:6379
jedis:
pool:
min-idle: 1
max-idle: 8
max-wait: 1000ms
max-active: 8
timeout: 2000ms
package com.jack.service;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
/**
* Created By Jack on 2018/9/20
*
* @author Jack
* @date 2018/9/20 15:03
* @Description:
*/
@Service
public class JedisRedisService {
@Autowired
private JedisCluster jedisCluster;
public void set(String key,String value){
jedisCluster.set(key, value);
}
public String get(String key) {
return jedisCluster.get(key);
}
@SuppressWarnings("unchecked")
public T get(String key, Class extends Serializable> c) {
String s = get(key);
return (T) JSONObject.parseObject(s,c);
}
public long set(String key,String value,int expireTime){
jedisCluster.set(key, value);
return jedisCluster.expire(key, expireTime);
}
public long set(String key, Object obj, int expireTime) {
String jsonString = JSONObject.toJSONString(obj);
return set(key, jsonString, expireTime);
}
public long del(String key) {
return jedisCluster.del(key);
}
/**
* 在名称为key的list尾添加元素
* @param key
* @param list
*/
public void add(String key,List list){
if(list != null && list.size() > 0){
String[] vals = list.toArray(new String[list.size()]);
jedisCluster.rpush(key, vals);
}
}
/**
*
* @param key
* @param value
*/
public void add(String key, String value) {
jedisCluster.rpush(key, value);
}
/**
* 返回名称为key的list的长度
* @param key
* @return
*/
public Long getSize(String key){
return jedisCluster.llen(key);
}
/**
* 返回并删除名称为key的list中的首元素
* @param key
* @return
*/
public String getFirst(String key){
return jedisCluster.lpop(key);
}
/**
* 从左获取数据
* @param key
* @param count 获取条数
* @return
*/
public List getLrange(String key, long count){
return getLrange(key, 0, count-1);
}
/**
* 从左获取数据(注意:开始下班0,结束下标1;总共获取2条数据)
* @param key
* @param start 开始下标(包含)
* @param end 结束下标(包含)
* @return
*/
public List getLrange(String key, long start, long end){
return jedisCluster.lrange(key, start, end);
}
/**
* 删除集合中元素
*
* @param key
* @param count 删除数量
*/
public void leftDel(String key, int count) {
for (int i = 0; i < count; i++) {
jedisCluster.lpop(key);
}
}
/**
* 获取keys
* @param pattern
* @return
*/
public TreeSet keys(String pattern){
TreeSet keys = new TreeSet<>();
Map clusterNodes = jedisCluster.getClusterNodes();
for(String k : clusterNodes.keySet()){
JedisPool jp = clusterNodes.get(k);
try (Jedis connection = jp.getResource()) {
keys.addAll(connection.keys(pattern));
} catch (Exception ignored) {
}
}
return keys;
}
public String rename(String oldKey, String newKey) {
return jedisCluster.rename(oldKey, newKey);
}
public List ll(String key) {
return jedisCluster.lrange(key, 0, -1);
}
public Long lpush(String key, String... va) {
return jedisCluster.lpush(key, va);
}
public void lpush(String key, List list) {
if(list != null && list.size() > 0){
String[] vals = list.toArray(new String[list.size()]);
jedisCluster.lpush(key, vals);
}
}
}
1)创建一个实体类
package com.jack.entity;
import lombok.Data;
import java.io.Serializable;
/**
* Created By Jack on 2019/7/10
*
* @author Jack
* @date 2019/7/10 20:17
* @Description:
*/
@Data
public class Person implements Serializable {
private static final long serialVersionUID = -2882592645848747970L;
private int age;
private String sex;
private String name;
}
2)测试controller
package com.jack.controller;
import com.jack.entity.Person;
import com.jack.service.JedisRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created By Jack on 2019/7/10
*
* @author Jack
* @date 2019/7/10 16:32
* @Description:
*/
@RestController
@RequestMapping("redis")
public class RedisTestController {
@Autowired
private JedisRedisService jedisRedisService;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 使用jedis插入key,value
* @return
*/
@RequestMapping("test1")
public String redisTest1() {
jedisRedisService.set("jack","rose");
System.out.println("插入字符串成功");
System.out.println("获取字符串:"+jedisRedisService.get("jack"));
return "success";
}
/**
* 使用StringRedisTemplate插入key,value
* @return
*/
@RequestMapping("test2")
public String redisTest2() {
stringRedisTemplate.opsForValue().set("jack2","rose2");
System.out.println("插入字符串成功");
System.out.println("获取字符串:"+stringRedisTemplate.opsForValue().get("jack2"));
return "success";
}
/**
* 使用jedis插入对象
* @return
*/
@RequestMapping("test3")
public String redisTest3() {
Person p = new Person();
p.setAge(18);
p.setName("jack");
p.setSex("男");
jedisRedisService.set("p",p,300);
System.out.println("插入字符串成功");
System.out.println("获取对象的值:"+jedisRedisService.get("p"));
return "success";
}
}
主类代码:
package com.jack;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Springboot2RedisApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Springboot2RedisApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("*************启动成功**********************");
}
}
启动程序:
使用postman访问:
http://localhost:9090/redis/test1
http://localhost:9090/redis/test2
http://localhost:9090/redis/test3
输出如下:
*************启动成功**********************
2019-07-10 20:46:58.593 INFO 12808 --- [nio-9090-exec-5] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-07-10 20:46:58.593 INFO 12808 --- [nio-9090-exec-5] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-07-10 20:46:58.598 INFO 12808 --- [nio-9090-exec-5] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
插入字符串成功
获取字符串:rose
插入字符串成功
获取字符串:rose2
插入字符串成功
获取对象的值:{"age":18,"name":"jack","sex":"男"}