做网站移交资料,湛江网站搜索优化,百度搜索浏览器,吕邵苍设计公司网站Spring Boot 集成 Redis 实现数据缓存#xff0c;只要添加一些注解方法#xff0c;就可以动态的去操作缓存了#xff0c;减少代码的操作。在这个例子中我使用的是 Redis#xff0c;其实缓存类型还有很多#xff0c;例如 Ecache、Mamercache、Caffeine 等。Redis 简介Redi… Spring Boot 集成 Redis 实现数据缓存只要添加一些注解方法就可以动态的去操作缓存了减少代码的操作。在这个例子中我使用的是 Redis其实缓存类型还有很多例如 Ecache、Mamercache、Caffeine 等。Redis 简介Redis 是一个开源高级的键值存储和一个适用的解决方案用于构建高性能可扩展的 Web 应用程序。Redis 相关的知识就不在这里赘述了感兴趣的可以公众号回复 Redis 看下 Redis 系列文章。下面我们在 Spring Boot 中集成 Redis 来实现数据缓存。Spring Boot 集成 Redis 实现缓存Spring Boot 集成 Redis 实现缓存主要分为以下三步加入 Redis 依赖加入 Redis 配置演示 Redis 缓存加入依赖首先创建一个项目在项目中加入 Redis 依赖项目依赖如下所示(由于使用 Redis 连接池需额外引入 commons-pool2)org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-data-redisorg.apache.commonscommons-pool2在 spring-boot-starter-data-redis 1.X 版本默认使用 Jedis 客户端在 2.X 版本默认开始使用 Lettuce 客户端如果习惯使用 Jedis 的话可以从 spring-boot-starter-data-redis 中排除 Lettuce 并引入 Jedis。加入配置在配置文件 application.properties 中配置 Redis 的相关参数具体内容如下#Redis 索引(0~15默认为 0)spring.redis.database0spring.redis.host127.0.0.1#Redis 密码如果没有就默认不配置此参数spring.redis.passwordspring.redis.port6379#Redis 连接的超时时间spring.redis.timeout1000#连接池最大连接数(使用负值表示没有限制)spring.redis.lettuce.pool.max-active20#连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.lettuce.pool.max-wait-1#连接池中的最大空闲连接spring.redis.lettuce.pool.max-idle10#连接池中的最小空闲连接spring.redis.lettuce.pool.min-idle0接下来在 config 包下创建一个 Redis 配置类 RedisConfig在配置类上加入注解 Configuration注入一个 CacheManager 来配置一些相关信息代码如下Configurationpublic class RedisConfig { Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration redisCacheConfiguration RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(30)) .prefixKeysWith(cache:user:) .disableCachingNullValues() .serializeKeysWith(keySerializationPair()) .serializeValuesWith(valueSerializationPair()); return RedisCacheManager.builder(factory) .withCacheConfiguration(user, redisCacheConfiguration).build(); } private RedisSerializationContext.SerializationPair keySerializationPair() { return RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()); } private RedisSerializationContext.SerializationPair valueSerializationPair() { return RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()); }}首先通过 RedisCacheConfiguration 生成默认配置然后对缓存进行自定义化配置比如过期时间、缓存前缀、key/value 序列化方法等然后构建出一个 RedisCacheManager其中通过 keySerializationPair 方法为 key 配置序列化valueSerializationPair 为 value 配置序列化。定义用户实体类在 domain 包下创建一个用户实体类public class User { private Long id; private String name; private String password; // 省略 getter/setter}在服务中使用 SpringCache 注解在 service 包下定义用户接口分别包含添加用户、查询用户、更新用户以及删除用户四个接口具体代码如下public interface UserService { void addUser(User user); User getUserById(Long id); User updateUser(User user); void deleteById(Long id);}然后编写实现类为了方便演示在这里使用 Map userMap没有去连接数据库其中用到的注解有 CacheConfig、Cacheable、CachePut 以及 CacheEvict具体代码如下ServiceCacheConfig(cacheNames user)public class UserServiceImpl implements UserService { Map userMap Collections.synchronizedMap(new HashMap());Overridepublic void addUser(User user) { userMap.put(user.getId(), user); }OverrideCacheable(key #id)public User getUserById(Long id) {if (!userMap.containsKey(id)) {return null; }return userMap.get(id); }OverrideCachePut(key #user.id)public User updateUser(User user) {if (!userMap.containsKey(user.getId())) {throw new RuntimeException(不存在该用户); } User newUser userMap.get(user.getId()); newUser.setPassword(user.getPassword()); userMap.put(newUser.getId(), newUser);return newUser; }OverrideCacheEvict(key #id)public void deleteById(Long id) { userMap.remove(id); }}在这里说下这几个注解CacheConfig 类级别的缓存注解允许共享缓存名称Cacheable 触发缓存入口一般用于查询操作根据 key 查询缓存.如果 key 不存在查询 db并将结果更新到缓存中。如果 key 存在直接查询缓存中的数据。CacheEvict 触发移除缓存根据 key 删除缓存中的数据。CacahePut 更新缓存一般用于更新和插入操作每次都会请求 db通过 key 去 Redis 中进行操作。如果 key 存在更新内容如果 key 不存在插入内容。最后在 controller 包下创建一个 UserController 类提供用户 API 接口(未使用数据库)代码如下RestControllerRequestMapping(/user)public class UserController { Autowired private UserService userService; GetMapping(/{id}) public ResponseEntity getUser(PathVariable Long id) { return ResponseEntity.status(HttpStatus.CREATED).body(userService.getUserById(id)); } PostMapping public ResponseEntity createUser(RequestBody User user) { userService.addUser(user); return ResponseEntity.status(HttpStatus.CREATED).body(SUCCESS); } PutMapping public ResponseEntity updateUser(RequestBody User user) { return ResponseEntity.status(HttpStatus.CREATED).body(userService.updateUser(user)); } DeleteMapping(/{id}) public ResponseEntity deleteUser(PathVariable Long id) { userService.deleteById(id); return ResponseEntity.status(HttpStatus.CREATED).body(SUCCESS); }}启动类添加开启缓存注解SpringBootApplicationEnableCachingpublic class RedisCacheApplication { public static void main(String[] args) { SpringApplication.run(RedisCacheApplication.class, args); }}EnableCaching 表明开启缓存Spring Boot 会自动配置 Redis 缓存的 CacheManager。启动项目先调用添加用户接口添加用户 wupxid 为 1在 getUserById 方法打断点第一次调用 getUser 接口获取用户的时候会运行到断点处第二次调用 getUser 不会运行到断点处而是直接从 Redis 中读取缓存数据。通过 Redis 可视化工具 RedisDesktopManager 查看结果如图所示到此为止我们就完成了 Spring Boot 与 Redis 的集成实现数据缓存。总结Spring Boot 集成 Redis 实现数据缓存还是比较轻松的Spring 提供了缓存注解使用这些注解可以有效简化编程过程大家可以自己动手实践下。本文的完整代码在 https://github.com/wupeixuan/SpringBoot-Learn 的 redis-cache 目录下。留言讨论最好的关系就是互相成就大家的点赞、在看、分享、留言四连就是我创作的最大动力。参考https://github.com/wupeixuan/SpringBoot-Learn完 ●Spring Boot 集成阿里云 OSS 进行文件存储●Spring Boot 集成 Elasticsearch 实战●Spring Boot 集成 WebSocket 实现服务端推送消息到客户端