redis-10-spring-boot

諸葛流雲發表於2017-04-23

[TOC]

說明

本文主要介紹使用spring-boot整合jedis的方式來操作redis。

至於jedis的單獨使用就不必多說了。

此處的整合方式有兩種:

  • 手動配置整合jedis

  • 使用spring-boot-starter-data-redis整合

1 手動配置整合jedis

1.1 jar依賴

<dependencies>
  
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
  </dependency>
  
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  
  <!--此處並不是直接使用spring提供的redis-starter-->
  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
  </dependency>
  
</dependencies>

1.2 配置

1.2.1 外部配置檔案

  • application.yaml

jedis:
  host: 127.0.0.1
  port: 6379
  pool:
    max-idle: 300
    min-idle: 10
    max-total: 600
    max-wait: 1000
    block-when-exhausted: true

1.2.2 java配置類(代替傳統的xml配置)

  • RedisConfig.java

package cn.hylexus.app.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    @Bean("jedis.config")
    public JedisPoolConfig jedisPoolConfig(//
            @Value("${jedis.pool.min-idle}") int minIdle, //
            @Value("${jedis.pool.max-idle}") int maxIdle, //
            @Value("${jedis.pool.max-wait}") int maxWaitMillis, //
            @Value("${jedis.pool.block-when-exhausted}") boolean blockWhenExhausted, //
            @Value("${jedis.pool.max-total}") int maxTotal) {

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(minIdle);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMaxTotal(maxTotal);
        // 連線耗盡時是否阻塞, false報異常,ture阻塞直到超時, 預設true
        config.setBlockWhenExhausted(blockWhenExhausted);
        // 是否啟用pool的jmx管理功能, 預設true
        config.setJmxEnabled(true);
        return config;
    }

    @Bean
    public JedisPool jedisPool(//
            @Qualifier("jedis.config") JedisPoolConfig config, //
            @Value("${jedis.host}") String host, //
            @Value("${jedis.port}") int port) {
        return new JedisPool(config, host, port);
    }
}

1.3 使用示例

package cn.hylexus.app.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisServiceImpl implements RedisService {

    // 此處直接注入即可
    @Autowired
    private JedisPool jedisPool;

    @Override
    public String get(String key) {
        Jedis jedis = this.jedisPool.getResource();
        String ret;
        try {
            ret = jedis.get(key);
        } finally {
            if (jedis != null)
                jedis.close();
        }
        return ret;
    }

    @Override
    public boolean set(String key, String val) {
        Jedis jedis = this.jedisPool.getResource();
        try {
            return "OK".equals(jedis.set(key, val));
        } finally {
            if (jedis != null)
                jedis.close();
        }
    }

}

1.4 簡單測試

package cn.hylexus.app.service;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import cn.hylexus.app.SpringBootRedisJedispoolApplicationTests;

public class RedisServiceImplTest extends SpringBootRedisJedispoolApplicationTests {

    @Autowired
    private RedisService redisService;

    @Test
    public void testGet() {
        // test set
        boolean status = this.redisService.set("foo", "bar");
        Assert.assertTrue(status);

        // test get
        String str = this.redisService.get("foo");
        Assert.assertEquals("bar", str);
    }

}

1.5 原始碼地址

https://github.com/hylexus/bl…

2 使用spring-boot-starter-data-redis

2.1 jar依賴

<dependencies>
  
  <!--此處使用spring提供的針對於redis的starter-->
  <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>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

2.2 配置

2.2.1 外部配置檔案

  • application.yaml

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: null
    pool:
      max-idle: 300
      min-idle: 10
      max-active: 600
      max-wait: 1000
    timeout: 0

2.2.2 java配置類

package cn.hylexus.app.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 例項化 RedisTemplate 物件
     * 
     */
    @Bean
    public RedisTemplate<String, Object> functionDomainRedisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        this.initRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 序列化設定
     */
    private void initRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
    }

    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

2.3 簡單測試

package cn.hylexus.app;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTests {

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testStringOps() {
        this.valueOperations.set("k1", "spring-redis");

        Boolean hasKey = this.redisTemplate.hasKey("k1");
        assertEquals(true, hasKey);

        Object str = this.valueOperations.get("k1");
        assertNotNull(str);
        assertEquals("spring-redis", str.toString());
    }
}

2.4 原始碼地址

https://github.com/hylexus/bl…