本篇主要講述如何使用基本的注解 @Cacheable @CachePut @CacheEvict 操作緩存
1.我們導(dǎo)入redis的依賴
<!--這里Redis我給了版本--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!--使用配置類時(shí),防止亂碼需要用到的包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
2.編寫配置類
@ConfigurationProperties(prefix = "spring.cache.redis") @Configuration public class RedisConfig { private Duration timeToLive = Duration.ZERO; public void setTimeToLive(Duration timeToLive) { this.timeToLive = timeToLive; } @Bean /** * 該bean只針對(duì)cache存入到數(shù)據(jù)亂碼問題 */ public RedisCacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解決查詢緩存轉(zhuǎn)換異常的問題 ObjectMApper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解決亂碼的問題) RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(timeToLive) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }
3.配置文件
#要連接的數(shù)據(jù)是哪個(gè) spring.redis.database=1 #數(shù)據(jù)連接地址 spring.redis.host=localhost #端口號(hào) spring.redis.port=6379 #連接超時(shí)時(shí)間 spring.redis.timeout=1s #最大連接數(shù) spring.redis.jedis.pool.max-active=20 #最大空閑連接 spring.redis.jedis.pool.max-idle=20 #最小空閑連接 spring.redis.jedis.pool.min-idle=10 #最大等待阻塞等待時(shí)間 spring.redis.jedis.pool.max-wait=-1ms #在寫入Redis時(shí)是否要使用key前綴 spring.cache.redis.use-key-prefix=true #key前綴 spring.cache.redis.key-prefix=dev #是否允許有null值 spring.cache.redis.cache-null-values=false #設(shè)置緩存存在時(shí)間,只針對(duì)cacheable存入數(shù)據(jù)有用 spring.cache.redis.time-to-live=120s
4.現(xiàn)在我們的環(huán)境準(zhǔn)備好了,開始編寫代碼
這里是pojo
@Table(name = "user1") public class User implements Serializable { @Id private Integer id; private String name; private String pwd; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + ''' + ", pwd='" + pwd + ''' + '}'; } }
這里是dao類
@org.Apache.ibatis.annotations.Mapper public interface UserMapper extends Mapper<User> { }
這里是在service類上使用注解
@CacheConfig(cacheNames = "user")//注意,用于同一配置給其它注解配置名稱 public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override @Cacheable(key="#p0")//該注解用于向緩存中存入數(shù)據(jù) public User findUser(Integer id) { System.out.println("查詢數(shù)據(jù)了"+id); User user = userMapper.selectByPrimaryKey(id); return user; } @Override @CachePut(key="#p0.id")//該注解用于更新緩存中的注解 public User updateUser(User user) { userMapper.updateByPrimaryKeySelective(user); return user; } @Override @CacheEvict(key="#p0")//該注解用于刪除緩存 public void deleteUser(Integer id) { userMapper.deleteByPrimaryKey(id); } @Override public List<User> findUsers() { return userMapper.selectAll(); } }
注意,這里需要說明一下,#p0代表第一個(gè)參數(shù),返回值默認(rèn)是方法的返回值,@Cacheable之類的注解必須要有value值,這里我在類上加@CacheConfig注解,使下面的注解有了同一個(gè)value值
這里是controller里面的代碼
@RestController @RequestMapping("/user") public class UserController { @Resource private UserService userService; @GetMapping public ResponseEntity<List<User>> findUsers(){ try { List<User> users = userService.findUsers(); return new ResponseEntity<>(users,HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping("/{id}") public ResponseEntity<User> findUser(@PathVariable("id")Integer id){ try { User user = userService.findUser(id); return new ResponseEntity<>(user, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @PutMapping public ResponseEntity<String> updateUser(@RequestBody User user){ try { userService.updateUser(user); return new ResponseEntity<>("修改成功",HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteUser(@PathVariable("id")Integer id){ try { userService.deleteUser(id); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } }
5.這里是數(shù)據(jù)庫的數(shù)據(jù)
6.好了,后臺(tái)代碼到這基本就完成了,現(xiàn)在自己編寫一下前臺(tái),完成測(cè)試
- 最后說一下需要注意的點(diǎn),配置文件中的時(shí)間配置規(guī)定了緩存存在的時(shí)間,這里我設(shè)置的是120s
- 這里的配置類必須這樣配置,否則,存入到數(shù)據(jù)的數(shù)據(jù)會(huì)亂碼
- 更新的時(shí)候,注意方法的返回值,否則數(shù)據(jù)存入的數(shù)據(jù)為null
來源:csdn 原文鏈接:https://blog.csdn.net/qq_43646524/article/details/102693454