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