本文共 18110 字,大约阅读时间需要 60 分钟。
参考《》中完成springboot多模块工程入门。
com.ct com.ct 1.0-SNAPSHOT 4.0.0 com.ct.redis 1.0.0.0 jar org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.projectlombok lombok
server: port: 8088spring: redis: host: 192.168.126.133 password: port: 6379 max-wait: 30000 # 连接池最大阻塞等待时间(使用负值,表示没有限制) max-active: 100 # 连接池最大连接数(使用负值,表示没有限制) max-idle: 20 # 连接池中的最大空闲连接 min-idle: 0 # 连接池中的最小空闲连接 timeout: 3000 # 连接超时
package com.ct.redis.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import lombok.extern.slf4j.Slf4j;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;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.*;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;/** * redis配置类 * * @Author LaoHa * @Date 2021/6/12 */@Slf4j@Configuration//开启注解@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport { /** * retemplate相关配置 * * @param factory * @return */ @Bean public RedisTemplateredisTemplate(RedisConnectionFactory factory) { log.info("RedisTemplate..."); RedisTemplate template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } /** * 对hash类型的数据操作 * * @param redisTemplate * @return */ @Bean public HashOperations hashOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForHash(); } /** * 对redis字符串类型数据操作 * * @param redisTemplate * @return */ @Bean public ValueOperations valueOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForValue(); } /** * 对链表类型的数据操作 * * @param redisTemplate * @return */ @Bean public ListOperations listOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForList(); } /** * 对无序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public SetOperations setOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForSet(); } /** * 对有序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public ZSetOperations zSetOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForZSet(); }}
package com.ct.redis.Utils;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.BoundListOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;/** * redisTemplate封装 * * @Author LaoHa * @Date 2021/6/12 */@Component@Slf4jpublic class RedisUtil { @Autowired private RedisTemplateredisTemplate; public RedisUtil(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } /** * 指定缓存失效时间 * * @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((Collection ) 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
package com.ct.redis.entity;import lombok.Data;import lombok.extern.slf4j.Slf4j;import java.io.Serializable;import java.util.Date;/** * @Author LaoHa * @Date 2021/6/12 */@Data@Slf4jpublic class UserEntity implements Serializable { private Long id; private String guid; private String name; private String age; private Date createTime;}
package com.ct.redis.controller;import com.ct.redis.Utils.RedisUtil;import com.ct.redis.entity.UserEntity;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.Date;/** * @Author LaoHa * @Date 2021/6/12 */@Slf4j@RequestMapping("/redis")@RestControllerpublic class RedisController { /** * redis中存储的过期时间60s */ private static int ExpireTime = 60; @Resource private RedisUtil redisUtil; @RequestMapping("set") public boolean redisset(String key, String value) { UserEntity userEntity = new UserEntity(); userEntity.setId(Long.valueOf(1)); userEntity.setGuid(String.valueOf(1)); userEntity.setName("zhangsan"); userEntity.setAge(String.valueOf(20)); userEntity.setCreateTime(new Date()); return redisUtil.set(key, value); } @RequestMapping("get") public Object redisget(String key) { return redisUtil.get(key); } @RequestMapping("expire") public boolean expire(String key) { return redisUtil.expire(key, ExpireTime); }}
package com.ct.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/**
运行AppRedis启动,
http://localhost:8088/redis/set?key=234&value=aaa
输出 true,表明运行成功。
浏览器输入:http://localhost:8088/redis/get?key=234
输出 aaa,表明缓存成功。
转载地址:http://llmdi.baihongyu.com/