亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.430618.com 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

本篇主要講述如何使用基本的注解 @Cacheable @CachePut @CacheEvict 操作緩存

1.我們導入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>
<!--使用配置類時,防止亂碼需要用到的包-->
 <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只針對cache存入到數據亂碼問題
 */
 public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
 RedisSerializer<String> redisSerializer = new StringRedisSerializer();
 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
 //解決查詢緩存轉換異常的問題
 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.配置文件

#要連接的數據是哪個
spring.redis.database=1
#數據連接地址
spring.redis.host=localhost
#端口號
spring.redis.port=6379
#連接超時時間
spring.redis.timeout=1s
#最大連接數
spring.redis.jedis.pool.max-active=20
#最大空閑連接
spring.redis.jedis.pool.max-idle=20
#最小空閑連接
spring.redis.jedis.pool.min-idle=10
#最大等待阻塞等待時間
spring.redis.jedis.pool.max-wait=-1ms
#在寫入Redis時是否要使用key前綴
spring.cache.redis.use-key-prefix=true
#key前綴
spring.cache.redis.key-prefix=dev
#是否允許有null值
spring.cache.redis.cache-null-values=false
#設置緩存存在時間,只針對cacheable存入數據有用
spring.cache.redis.time-to-live=120s

4.現在我們的環境準備好了,開始編寫代碼

這里是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")//該注解用于向緩存中存入數據
 public User findUser(Integer id) {
 System.out.println("查詢數據了"+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代表第一個參數,返回值默認是方法的返回值,@Cacheable之類的注解必須要有value值,這里我在類上加@CacheConfig注解,使下面的注解有了同一個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.這里是數據庫的數據

SpringBoot使用Redis實現 自動緩存 更新 刪除

 

6.好了,后臺代碼到這基本就完成了,現在自己編寫一下前臺,完成測試

  • 最后說一下需要注意的點,配置文件中的時間配置規定了緩存存在的時間,這里我設置的是120s
  • 這里的配置類必須這樣配置,否則,存入到數據的數據會亂碼
  • 更新的時候,注意方法的返回值,否則數據存入的數據為null

來源:csdn 原文鏈接:https://blog.csdn.net/qq_43646524/article/details/102693454

分享到:
標簽:SpringBoot
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定