本文共 18519 字,大约阅读时间需要 61 分钟。
学习springboot项目整合redis,首先贴一下项目的截图
第一步:
引入依赖:pom.xml
这里引入了org.springframework.boot spring-boot-starter-data-redis redis.clients jedis 2.9.0
spring-boot-starter-data-redis还有
redis.clients
不引入 redis.clients的情况下JedisPoolConfig的引入会出现问题(个人测试得出的结论)
第二步:配置
首先 创建一个redis的配置文件 redis.properties
#Matser的ip地址redis.hostName=127.0.0.1#端口号redis.port=6379#如果有密码redis.password=#客户端超时时间单位是毫秒 默认是2000redis.timeout=10000 #最大空闲数redis.maxIdle=300 #连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal#redis.maxActive=600#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性redis.maxTotal=1000 #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。redis.maxWaitMillis=1000 #连接的最小空闲时间 默认1800000毫秒(30分钟)redis.minEvictableIdleTimeMillis=300000 #每次释放连接的最大数目,默认3redis.numTestsPerEvictionRun=1024 #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1redis.timeBetweenEvictionRunsMillis=30000 #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个redis.testOnBorrow=true #在空闲时检查有效性, 默认falseredis.testWhileIdle=true #redis集群配置spring.redis.cluster.nodes=192.168.177.128:7001,192.168.177.128:7002,192.168.177.128:7003,192.168.177.128:7004,192.168.177.128:7005,192.168.177.128:7006spring.redis.cluster.max-redirects=3#哨兵模式#redis.sentinel.host1=192.168.177.128#redis.sentinel.port1=26379#redis.sentinel.host2=172.20.1.231#redis.sentinel.port2=26379
后面的集群 以及哨兵模式还没有亲测 但是添加了也不影响
编写 RedisConfig文件
package com.szt.springbootredis.config;import com.szt.springbootredis.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.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.StringRedisSerializer;import redis.clients.jedis.JedisPoolConfig;@Configuration@PropertySource("classpath:redis.properties")public class RedisConfig { @Value("${redis.maxIdle}") private Integer maxIdle; @Value("${redis.maxTotal}") private Integer maxTotal; @Value("${redis.maxWaitMillis}") private Integer maxWaitMillis; @Value("${redis.minEvictableIdleTimeMillis}") private Integer minEvictableIdleTimeMillis; @Value("${redis.numTestsPerEvictionRun}") private Integer numTestsPerEvictionRun; @Value("${redis.timeBetweenEvictionRunsMillis}") private long timeBetweenEvictionRunsMillis; @Value("${redis.testOnBorrow}") private boolean testOnBorrow; @Value("${redis.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.redis.cluster.nodes}") private String clusterNodes; @Value("${spring.redis.cluster.max-redirects}") private Integer maxRedirectsac; /** * JedisPoolConfig 连接池 * @return */ @Bean public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 最大空闲数 jedisPoolConfig.setMaxIdle(maxIdle); // 连接池的最大数据库连接数 jedisPoolConfig.setMaxTotal(maxTotal); // 最大建立连接等待时间 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟) jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3 jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun); // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1 jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 jedisPoolConfig.setTestOnBorrow(testOnBorrow); // 在空闲时检查有效性, 默认false jedisPoolConfig.setTestWhileIdle(testWhileIdle); return jedisPoolConfig; } /** * 单机版配置 * * @param @param jedisPoolConfig * @param @return * @return JedisConnectionFactory * @throws * @Title: JedisConnectionFactory * @autor lpl * @date 2018年2月24日 */ @Bean public JedisConnectionFactory JedisConnectionFactory(JedisPoolConfig jedisPoolConfig) { JedisConnectionFactory JedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig); //连接池 JedisConnectionFactory.setPoolConfig(jedisPoolConfig); //IP地址 JedisConnectionFactory.setHostName("127.0.0.1"); //端口号 JedisConnectionFactory.setPort(6379); //如果Redis设置有密码 //JedisConnectionFactory.setPassword(password); //客户端超时时间单位是毫秒 JedisConnectionFactory.setTimeout(5000); return JedisConnectionFactory; } /** * 实例化 RedisTemplate 对象 * * @return */ @Bean public RedisTemplatefunctionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate redisTemplate = new RedisTemplate<>(); initDomainRedisTemplate(redisTemplate, redisConnectionFactory); return redisTemplate; } /** * 设置数据存入 redis 的序列化方式,并开启事务 * * @param redisTemplate * @param factory */ private void initDomainRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) { //如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String! redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer());// redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());// redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // 开启事务 redisTemplate.setEnableTransactionSupport(true); redisTemplate.setConnectionFactory(factory); } /** * 注入封装RedisTemplate * * @return RedisUtil * @throws * @Title: redisUtil * @autor lpl * @date 2017年12月21日 */ @Bean(name = "redisUtil") public RedisUtil redisUtil(RedisTemplate redisTemplate) { RedisUtil redisUtil = new RedisUtil(); redisUtil.setRedisTemplate(redisTemplate); return redisUtil; }}
在测试的时候
// redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());// redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
总是报错,暂时不管 直接注掉,不影响
编写utils文件 ,有这个 方便很多,也是copy得到的
package com.szt.springbootredis.utils;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.util.CollectionUtils;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;public class RedisUtil { private RedisTemplateredisTemplate; public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } //=============================common============================ /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ 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) * @return */ 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) * @return */ 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 * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map
此时,配置完成,需要测试 写一个service和一个model来测试下
service:
@Servicepublic class RedisService { @Autowired private RedisUtil redisUtil; public void addUser(User user){ boolean u = redisUtil.set("u", user); System.out.println("u = " + u); } public void getUser(String key){ User user = (User) redisUtil.get(key); System.out.println("user ===== " + user.toString()); }}
model:
public class User implements Serializable { private String name; private Integer age;//省略getter和setter}
创建测试:
@RunWith(SpringRunner.class)@SpringBootTestpublic class redisServiceTest { @Autowired private RedisService redisService; @Test public void addUser() { User user = new User(); user.setAge(18); user.setName("susan"); redisService.addUser(user); } @Test public void getUser() { String key ="u"; redisService.getUser(key); }}
测试结果:
至此,简单实现了springboot整合redis的功能,哨兵和集群稍后研究。
此文总结于:https://blog.csdn.net/plei_yue/article/details/79362372