Redis简单理解,Redis可以作为一个极速(内存)数据,能够解决数据库响应慢的一个辅助工具,基于这一点,就有市场了
Redis 是一个高性能的key-value数据库。 redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部分场合可以对关系数据库起到很好的补充作用。
安装部分这里略过,直接到使用
添加依赖包
1 2 3 4 5 6 7 8 9 10 11 12 13
| <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
|
添加配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| spring: redis.database: 0 redis.host: localhost redis.port: 6379 redis.password: redis.lettuce.pool.max-active: 8 redis.lettuce.pool.max-wait: -1 redis.lettuce.pool.max-idle: 8 redis.lettuce.pool.min-idle: 0
|
Redis Cached的应用
添加配置,这个功能可以不需要重写,关键在@EnableCaching
要添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {
@Bean public KeyGenerator keyGenerator() { return (target, method, 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(); }; } }
|
验证
1 2 3 4 5 6 7 8
| @RequestMapping("/test-redis") @Cacheable(value = "user-key") public User testRedis() { User user = new User("test", "aabbcc", "123456", "123456789"); System.out.println("无缓存的时候调用"); return user; }
|
缓存注解可以参考https://mrbird.cc/Spring-Boot%20cache.html
Session Redis的应用
添加配置
1 2 3 4
| @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 24 * 3600 * 30) public class SessionConfig { }
|
验证
1 2 3 4 5 6 7 8 9
| @RequestMapping("/test-redis-uuid") public String uuid(HttpSession session) { UUID uid = (UUID) session.getAttribute("uid"); if (uid == null) { uid = UUID.randomUUID(); } session.setAttribute("uid", uid); return session.getId(); }
|
参考
https://github.com/ityouknow/spring-boot-examples/blob/master/spring-boot-redis/
https://github.com/piomin/sample-spring-redis