springboo-redis详解编程语言
2023-06-13 09:11:46 时间
springboot中使用redis:
(1).使用redis工具类手动操作缓存
(2).使用cacheable注解到方法头,自动创建缓存数据
1.安装redis
https://github.com/dmajkic/redis/downloads
下载后解压:
cmd中启动redis:
启动:
D:
cd D:/Program Files/redis2.4.5/64bit
redis-server.exe redis.conf
2.安装Redis Desktop Manager工具操作redis:
3.开始编码
添加redis依赖
dependency groupId org.springframework.boot /groupId artifactId spring-boot-starter-redis /artifactId /dependency
配置redis
package com.mlxs.springboot05.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; * RedisConfig类描述: redis配置类 * @author yangzhenlong * @since 2017/2/16 @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ /** * key生成策略 * @return @Bean public KeyGenerator keyGenerator(){ return new KeyGenerator() { @Override public String generate(Object targetClass, Method targetMethod, Object... params) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(targetClass.getClass().getName()); stringBuffer.append("." + targetMethod.getName()); for (Object param : params){ stringBuffer.append("_" + param.toString()); return stringBuffer.toString(); /** * redis缓存配置 * @param redisTemplate * @return @Bean public CacheManager cacheManager(RedisTemplate redisTemplate){ RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate); redisCacheManager.setDefaultExpiration(60 * 5);//设置过期时间 单位:秒 Map String, Long expires = new HashMap (); expires.put("test", 300L); redisCacheManager.setExpires(expires);//设置value过期时间 return redisCacheManager; /** * 设置redisTemplate * @param factory * @return @Bean public RedisTemplate String, String redisTemplate(RedisConnectionFactory factory){ StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory); //设置序列化方式 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); stringRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer); stringRedisTemplate.afterPropertiesSet(); return stringRedisTemplate; }
3.1 使用redis工具类,手动操作redis
package com.mlxs.springboot05.redis.use01;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; * RedisUtil类描述: * @author yangzhenlong * @since 2017/2/16 @Component public class RedisUtil { @Autowired private RedisTemplate redisTemplate; /** * 根据key删除 * @param key public void remove(String key){ if(this.isExistKey(key)){ redisTemplate.delete(key); /** * 根据key批量删除 * @param keys public void remove(String... keys){ for(String key : keys){ this.remove(key); /** * 根据key判断是否存在对应的value * @param key * @return public boolean isExistKey(String key){ return redisTemplate.hasKey(key); /** * 根据key获取值 * @param key * @return public Object get(String key){ ValueOperations valueOperations = redisTemplate.opsForValue(); return valueOperations.get(key); /** * 写入缓存 * @param key * @param value * @return public boolean set(String key, Object value){ try { ValueOperations valueOperations = redisTemplate.opsForValue(); valueOperations.set(key, value); return true; }catch (Exception e){ e.printStackTrace(); return false; /** * 写入缓存 * @param key * @param value * @param expireTime * @return public boolean set(String key, Object value, Long expireTime){ try { ValueOperations valueOperations = redisTemplate.opsForValue(); valueOperations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); return true; }catch (Exception e){ e.printStackTrace(); return false; }
测试工具类:
import com.mlxs.springboot05.redis.MainApp; import com.mlxs.springboot05.redis.use01.RedisUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Arrays; import java.util.List; * Use01Test类描述: * @author yangzhenlong * @since 2017/2/16 @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(MainApp.class) public class Use01Test { @Autowired private RedisUtil redisUtil; @Test public void test(){ //设置值 List String stringList = Arrays.asList("aaa", "bbb", "ccc"); boolean setResult = redisUtil.set("strList", stringList); System.out.println("保存redis结果:" + setResult); //获取值 Object getResult = redisUtil.get("strList"); System.out.println("查询redis结果:" + getResult); }
查看测试结果:
3.2 使用@Cacheable 注解,自动添加缓存
package com.mlxs.springboot05.redis.use02;
import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; * TestMethod类描述: * @author yangzhenlong * @since 2017/2/16 @RestController @RequestMapping("/redis") public class RedisController { @RequestMapping("/str/{str}") @Cacheable(value = "redisTest") public String queryStr(@PathVariable String str){ System.out.println("---请求参数---" + str); return "queryStr return: " + str; }
启动mainApp后,访问:http://localhost:8080/redis/str/8888
发现后台打印:
当再次请求http://localhost:8080/redis/str/8888,发现后台没有打印任何数据,说明直接请求redis返回结果,查看redis:
可以看到redis中已经有数据了。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16961.html
cjavaxml相关文章
- Springboot+Redis序列化坑详解编程语言
- Redis必知必会:深入详解(redis深入详解)
- 分析处理Redis慢日志的技巧(redis慢日志)
- Redis新手指南:一步一步搞定(redis新手入门详解)
- 时间Redis在Java中设置过期时间的实现方法(redisjava过期)
- 记录日志使用Node Redis实现快速的日志记录(node使用redis)
- Redis连接步骤详解,轻松应对开发需求(redis怎么链接)
- 处理借助Redis,轻松承载千万数据(redis千万数据)
- Redis优化:提升写入性能(redis写入性能)
- 详解 Redis:原理、特性及应用场景(redis原理详解)
- 深入探究Redis集群:全面解析架构设计与使用方法(redis集群详解)
- 使用Redis保存大量数据表(数据表存储到redis)
- Redis之大key背后的故事(什么叫redis大key)
- 学习R语言,连接Redis数据库(r语言连接redis)
- 安装Redis时需要Lua的支持(redis需要安装lua)
- Redis集群安装指南安装在本地还是云端(redis集群安装在哪里)
- Redis集群理解它的意义(redis集群啥意思)
- 深入浅出Redis集合的实现原理(redis集合的实现原理)
- 借助Redis实现高效的键排序(redis 键排序)
- 深入浅出Redis 设计模式探索(redis设计详解)
- Redis自定义监控从性能优化到故障排除(redis自定义监控)