springboot中redis的集成与使用

springboot中提供了对redis的lettuce和jedis两个客户端的自动配置功能的支持,而在使用spring-boot-starter-data-redis帮助我们快速集成redis时,其是默认支持lettuce的。下面来看一下使用spring-boot-starter-data-redis如何快速集成与使用redis。

依赖引入

在pom文件中加入starter和common-pool2(连接池使用)包,如下所示:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.2</version>
        </dependency>
自动配置

application.yml文件中加入redis的连接配置和连接池配置,如下所示:

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 6
    timeout: 2000
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: 1000
简单使用

先看一下整体的简单案例代码:

@Component
public class RedisDemo implements CommandLineRunner {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void run(String... args) throws Exception {
        redisTemplate.opsForValue().set("key", "hello");
        String value = (String) redisTemplate.opsForValue().get("key");
        System.out.println(value);

        stringRedisTemplate.opsForValue().set("string-key", "hello");
        value = stringRedisTemplate.opsForValue().get("string-key");
        System.out.println(value);
    }
}

这里我们实现CommandLineRunner接口,使得项目启动便可以执行该案例代码,这里就不再多说。

我们还能看到其中用到了RedisTemplateStringRedisTemplate两个模板类,帮助使用redis。那么两个有什么区别呢?区别在于他们使用序列化方式不一样,对于RedisTemplate来说,如果不指定序列化方式就是用的默认序列化方式JdkSerializationRedisSerializer,而 StringRedisTemplate是使用字符串序列化方式。

StringRedisTemplate源码如下:

/**
 * String-focused extension of RedisTemplate. Since most operations against Redis are String based, this class provides
 * a dedicated class that minimizes configuration of its more generic {@link RedisTemplate template} especially in terms
 * of serializers.
 * <p/>
 * Note that this template exposes the {@link RedisConnection} used by the {@link RedisCallback} as a
 * {@link StringRedisConnection}.
 *
 * @author Costin Leau
 * @author Mark Paluch
 */
public class StringRedisTemplate extends RedisTemplate<String, String> {

	/**
	 * Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}
	 * and {@link #afterPropertiesSet()} still need to be called.
	 */
	public StringRedisTemplate() {
		setKeySerializer(RedisSerializer.string());
		setValueSerializer(RedisSerializer.string());
		setHashKeySerializer(RedisSerializer.string());
		setHashValueSerializer(RedisSerializer.string());
	}

	/**
	 * Constructs a new <code>StringRedisTemplate</code> instance ready to be used.
	 *
	 * @param connectionFactory connection factory for creating new connections
	 */
	public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
		this();
		setConnectionFactory(connectionFactory);
		afterPropertiesSet();
	}

	protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
		return new DefaultStringRedisConnection(connection);
	}
}

可以看到其对key、value、hashKey、hashValue均设置的是字符串序列化,且是UTF-8编码,RedisSerializer.string()内容如下:

	static RedisSerializer<String> string() {
		return StringRedisSerializer.UTF_8;
	}

所以,我们自己在使用的时候,得根据自己的项目的情况和规范来给RedisTemplate设置特定的序列化方式,又或者像StringRedisTemplate一样,实现一个自己特定序列化template模板。

案例源码

案例源码地址: https://github.com/lazycece/springboot-actual-combat/tree/master/springboot-ac-redis

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值