(1)添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
(2)在配置中心里添加redis配置
spring.datasource.password=123456
spring.datasource.username=root
spring.datasource.url=jdbc:mysql://localhost:3306/user?serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.redis.host=192.168.28.69
spring.redis.port=6381
logging.level.com.springboot1.demo.mapper=debug
(3)实体类User
package com.springboot1.demo.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName(value = "user")
public class User {
private Long id;
private String uName;
private Integer age;
private String email;
private Integer deleted;
private Date createTime;
private Date updateTime;
}
(4)接口类mapper,使用通用mapper
package com.springboot1.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.springboot1.demo.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
(5)启动类,加入包扫描,加入开启缓存注解
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@MapperScan(basePackages = {"com.springboot1.demo.mapper"})
@EnableCaching //开启缓存注解
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
(6)controller层
package com.springboot1.demo.controller;
import com.springboot1.demo.entity.User;
import com.springboot1.demo.service.UserService;
import com.springboot1.demo.service.UserService2;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("byId")
public User byId( Long id){
System.out.println(id);
return userService.findById(id);
}
@PutMapping("update")
public User update(User user){
return userService.update(user);
}
@DeleteMapping("delete")
public String delete( Long id){
return userService.delete(id);
}
@PostMapping("insert")
public String insert(User user){
return userService.insert(user);
}
}
(7)在service业务层中相应的方法上加入缓存注解
package com.springboot1.demo.service;
import com.springboot1.demo.entity.User;
import com.springboot1.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserService {
@Resource
private UserMapper userMapper;
@Autowired
private RedisTemplate redisTemplate;
//1.如果缓存中存在该记录,则不会执行方法体。如果不存在则执行方法体并把查询的结果再放回前放入到缓存中
@Cacheable(cacheNames = "user::findById",key = "#id")
public User findById(Long id){
//2.如果不存在则查询数据库 并把查询的结果放入redis中
User user=userMapper.selectById(id);
return user;
}
//1.把缓存中指定数据删除 并执行方法体中的代码
@CacheEvict(cacheNames = "user::findById",key = "#id")
public String delete(Long id){
//2. 删除数据库中具有的数据
userMapper.deleteById(id);
return "删除成功";
}
//1.把数据库中的数据修改后,把返回的数据放入到缓存中
@CachePut(cacheNames ="user::findById",key = "#user.id" )
public User update(User user){
//2.再修改数据库中的数据
userMapper.updateById(user);
return user;
}
public String insert(User user){
userMapper.insert(user);
return "添加成功";
}
}
(8)配置config类
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig {
//比如验证码
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
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);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public CacheManager 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);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600)) //缓存过期10分钟 ---- 业务需求。
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))//设置key的序列化方式
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) //设置value的序列化
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}