springboot整合redis


步驟:

一、引入redis的starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、在springboot配置文件中配置連接redis的主機地址

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.1.6:3306/spring_cache?useUnicode=true\
  &characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
mybatis.configuration.map-underscore-to-camel-case=true
logging.level.com.xj.springboot.mapper=debug
spring.redis.host=192.168.1.6

三、使用

當我們導入了redis的starter后,springboot中的自動配置類RedisAutoConfiguration就生效了,RedisAutoConfiguration自動配置類會自動往容器中添加兩個組件:StringRedisTemplate和RedisTemplate。我們要使用的話直接通過Autowired注解將這兩個組件注入就可以使用了。

@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
  • StringRedisTemplate:用於操作key和value都是字符串的數據。
  • RedisTemplate:用於操作key和value都是對象的數據。

 注意:使用RedisTemplate操作對象時,對象必須是可序列化的,即需要實現序列化接口。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM