Spring Boot + Redis

使用Spring Boot包裝好的RedisTemplate對Redis進行快取機制。

1.pom.xml加入依賴

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

2.application.properties加入redis相關設定

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=xxxxxxx
spring.redis.database=0
spring.redis.timeout=300000
spring.redis.pool.max-active=1024
spring.redis.pool.max-wait=50
spring.redis.pool.max-idle=50
spring.redis.pool.min-idle=10
spring.redis.pool.testOnBorrow=true
spring.redis.pool.testOnReturn=true
spring.redis.lettuce.pool.max-active=1024
spring.redis.lettuce.pool.max-wait=10
spring.redis.lettuce.pool.max-idle=20
spring.redis.lettuce.pool.min-idle=10
spring.redis.lettuce.shutdown-timeout=300000

3.測試程式,寫入與取出快取資料

package com.liongogo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/redis/add")
    public String addRedis() {
        redisTemplate.opsForValue().set("liongogoRedisTest", "I am Lion GoGo");
        return "加入成功";
    }

    @RequestMapping("/redis/get")
    public Object getRedis() {
        Object value = redisTemplate.opsForValue().get("liongogoRedisTest");
        return value;
    }
}