在 Spring Boot 中使用 Redis
阿新 • • 發佈:2020-10-26
準備工作
Spring Boot 官方提供了 spring-boot-starter-data-redis
依賴,可以很方便的操作 redis。
從 Spring Boot 2.1.5 版本之後,遠端連線 Redis,必須使用 Spring Boot Security,當然,本地連線是不需要的。
redis 連線池有 lettuce 和 jedis 兩種,Spring Boot 2.x.x 版本預設使用的 lettuce 客戶端。
關於 lettuce 和 jedis 的異同,參考文章:Redis連線池Lettuce Jedis 區別
pom.xml 檔案所需依賴如下:
<dependencies> <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>
application.properties 配置檔案如下:
# 配置 Redis 的基本屬性
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=0
我在 Windows 本地安裝的 redis,預設是沒有密碼,所以這裡不需要配置密碼。
如果要配置密碼,參考文章:redis如何設定密碼
示例
新建一個 HelloController
類,寫入:
@RestController public class HelloController { @Autowired StringRedisTemplate stringRedisTemplate; @GetMapping("/set") public void set(){ ValueOperations<String, String> ops = stringRedisTemplate.opsForValue(); ops.set("name", "hahaha"); } @GetMapping("/get") public void get(){ ValueOperations<String, String> ops = stringRedisTemplate.opsForValue(); System.out.println(ops.get("name")); } }
啟動專案,先在瀏覽器訪問 http://localhost:8080/set
,再訪問 http://localhost:8080/get
,控制檯的輸出如下:
關於 StringRedisTemplate
這裡用到了 StringRedisTemplate
,這是 Spring Boot 官方自帶的操作 Redis 資料庫的模板。
StringRedisTemplate
的原始碼如下:
public class StringRedisTemplate extends RedisTemplate<String, String> { public StringRedisTemplate() { this.setKeySerializer(RedisSerializer.string()); this.setValueSerializer(RedisSerializer.string()); this.setHashKeySerializer(RedisSerializer.string()); this.setHashValueSerializer(RedisSerializer.string()); } public StringRedisTemplate(RedisConnectionFactory connectionFactory) { this(); this.setConnectionFactory(connectionFactory); this.afterPropertiesSet(); } protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) { return new DefaultStringRedisConnection(connection); } }
可以看到,StringRedisTemplate 繼承了 RedisTemplate,而 RedisTemplate 是在Spring Boot 中操作 redis 的基本模板。
每天學習一點點,每天進步一點點。