SpringBoot程序先查询redis,redis没有缓存,再查询MySQL数据库,最后将查到的数据缓存到MySQL。
废话不多说直接上代码:
1、Mapper文件
import com.example.redis.redistudy.pojo.UserRedis;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserRedisDao {
@Select("select * from user_redis")
List<UserRedis> getUserRedisList();
}
2、数据库对应的实体类,使用注解方式实现实体类实现序列化接口Serializable
import lombok.Data;
import java.io.Serializable;
@Data
public class UserRedis implements Serializable {
private Integer id;
private String name;
private Integer age;
}
3、控制层:
import com.example.redis.redistudy.mapper.UserRedisDao;
import com.example.redis.redistudy.pojo.UserRedis;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/userRedis")
public class UserRedisController {
@Resource
private UserRedisDao userRedisDao;
@GetMapping("/getUserRedisList")
@Cacheable(cacheNames = "members",key= "'getUserRedisList'")
public List<UserRedis> getUserRedisList(){
return userRedisDao.getUserRedisList();
}
}
这里需要注意的是,使用@Cacheable注解时需要注意,key=后面的双引号里面必须加单引号
@Cacheable(cacheNames = "members",key= "'getUserRedisList'")
然后使用这个注解必须要在springboot的启动类里面加上@EnableCaching和MapperScan扫描注解:
4、配置文件:
spring: redis: host: 服务器公网ip password: 密码 port: 6379 database: 0 datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://ip:端口号/数据库名?useUnicode=true&serverTimezone=UTC username: 用户名 password: 密码
按照这样写就行了,切记datasource不要写成database,估计只有我一个人写成这样吧!!
看一下效果:
redis中没有数据:
mysql中的数据:
然后使用url访问一下:
再看看此时的redis:
先去查询redis,redis没有数据再去查询mysql,再将查到的数据缓存到redis中;如果redis中能查询到数据,那么就不会再去查询mysql,那么,这里有一个问题就是redis和mysql数据的一致性问题,此时改了mysql数据库的数据之后,redis数据是不会个更新的,除非你先把redis的数据清除掉,那么每次都这样操作,很难受,后面一起学习如何解决这个数据一致性问题。