【西瓜皮】Spring Boot 2.x 整合 Redis(一)

Spring Boot 2 整合 Redis(一)

Spring Boot 2.0.3簡單整合Redis

IDEA Spring Initialzr 建立工程:選上Redis依賴項

clipboard.png

Maven依賴

// Spring Boot 1.5版本的依賴下artifactId是沒有data的
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

application.yml文件的配置,其中Jedis配置有默認值,Spring Boot 2後默認的鏈接池是lettuce,後面會講。

server:
  port: 6868

spring:
  redis:
    database: 0 # 0-15db
    host: 127.0.0.1
    port: 6379
    password:
    timeout: 1200
    # Jedis的配置,能夠不配置,有默認值(RedisProperties類中有指定默認值)
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1

配置完能夠直接注入使用

clipboard.png

// 測試StringRedisTemplate
    @GetMapping("/testStringRedisTemplate")
    public String testStringRedisTemplate() {
        String now = LocalDateTime.now().toString();
        stringRedisTemplate.opsForValue().set("key_" + now, now);
        return now;
    }

結果以下:redis

clipboard.png

在這裏,實際上不多直接使用RedisTemplate<Object,Object> redisTemplate,通常是寫Redis的配置類自定義RedisTemplate,接下來就實現自定義customRedisTemplate。spring

customRedisTemplate

@Configuration
public class RedisConfig {
    /**
     * 自定義RedisTemplate
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Student> customRedisTemplate(
            RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Student> rt = new RedisTemplate<>();
        // 實例化Jackson的序列化器
        Jackson2JsonRedisSerializer<Student> serializer
                = new Jackson2JsonRedisSerializer<Student>(Student.class);
        // 設置value值的序列化器爲serializer
        rt.setValueSerializer(serializer);
        rt.setHashValueSerializer(serializer);
        // 設置key鍵的序列化器爲serializer
        rt.setKeySerializer(new StringRedisSerializer());
        rt.setHashKeySerializer(new StringRedisSerializer());
        // 設置redis鏈接工廠(線程安全的)
        rt.setConnectionFactory(connectionFactory);
        return rt;
    }
}

測試自定義RedisTemplate的用例安全

@PostMapping("/add")
    public String add(@RequestBody Student student) {
        System.out.println(student);
        customRedisTemplate.opsForValue().set("key_" + student.getId(), student);
        return "add success";
    }

啓動Spring Boot並經過Restlet測試:app

clipboard.png

結果以下:spring-boot

clipboard.png

到此,簡單的整合Redis已經成功。接下來是cache註解。測試

相關文章
相關標籤/搜索