SpringBoot_03_Redis:SpringBoot添加redis支持非常简单,已经做好了starter。
org.springframework.boot spring-boot-starter-data-redis
只需要在application.properties文件中配置redis参数即可。
# REDIS (RedisProperties) # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=0
通过以上配置,即可使用redis读写数据。
@RestController @RequestMapping("redis/string") public class StringRedisController { @Autowired private StringRedisTemplate stringRedisTemplate; @Resource(name = "stringRedisTemplate") private ValueOperationsvalOpsStr; @RequestMapping("set") public String setKeyAndValue(String key, String value){ valOpsStr.set(key, value); return key + ": " + value; } @RequestMapping("get") public String getKey(String key){ return valOpsStr.get(key); } }
通过注入StringRedisTemplate,即可访问reids。
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间 rcm.setDefaultExpiration(5); // 秒 return rcm; } }
@RestController @RequestMapping("redis/object") public class ObjectRedisController { @Autowired private PersonDao personDao; @RequestMapping("/setPerson") public String set(String id, String name,Integer age){ Person person = new Person(id, name, age); personDao.save(person); return person.toString(); } @RequestMapping("/getPerson") @Cacheable(value="user-key") public Person getPerson(String id){ System.out.println("从数据库获取"); return personDao.getPerson(id); } }