Redis结合SpringBoot

Redis 与 SpringBoot 整合有两种方式,第一种是使用 Jedis,它是 Redis 官方推荐的面向 Java 的操作 Redis 的客户端,第二种是使用 RedisTemplate,它是 SpringDataRedis 中对 JedisApi 的高度封装。我此次使用的是RedisTemplate。

Maven依赖

首先要加入 Redis 相关依赖

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

application.properties中加入redis相关配置

# Redis数据库索引(默认为0)  
spring.redis.database=0  
# Redis服务器地址  
spring.redis.host=192.168.0.24  
# Redis服务器连接端口  
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)  
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)  
spring.redis.pool.max-active=200  
# 连接池最大阻塞等待时间(使用负值表示没有限制)  
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接  
spring.redis.pool.max-idle=10 
# 连接池中的最小空闲连接  
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)  
spring.redis.timeout=1000

配置RedisTemplate

首先 Spring 是对 RedisTemplate 做了自动配置的(在 RedisAutoConfiguration 类中)

@Configuration
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }
 
    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
 
    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

所以当添加 Redis 依赖后,SpringBoot 会自动帮我们在容器中生成一个 RedisTemplate 和一个 StringRedisTemplate,但是,我们可以看到这个 RedisTemplate 的泛型是 <Object,Object>,在代码中会不可避免的需要类型转换,这样不够安全,也过于麻烦,而且 RedisTemplate 没有设置序列化方式,所以,我们需要自己配置 RedisTemplate。
这个时候注意一下 @ConditionalOnMissingBean 这个注解的作用:在当前 Spring 上下文中不存在某个对象时,才会实例化一个 Bean。
因此当你依赖中加入 Redis 再启动后,SpringBoot 默认会自动给你实例化一个 RedisTemplate 。但是,它会自动给你实例化的条件是当前上下文中没有 RedisTemplate 对象。所以当我们自己手动给实例化一个 redisRemplate 对象后,SpringBoot 的就不会再给你实例化一个 RedisTemplate 对象了。
那为啥手动实例化一个 RedisTemplate 对象?因为要加一些定制化的东西,比如:key 的序列化方式,value 的序列化方式等。
所以我们需要配置 RedisTemplate:

package com.nowcoder.community.config;
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.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 设置key的序列化的方式
        template.setKeySerializer(RedisSerializer.string());
        // 设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        // 设置hash的key的序列化的方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置hash的value的序列化的方式
        template.setHashValueSerializer(RedisSerializer.json());
        template.afterPropertiesSet();
        return template;
    }
}

接下来就可以用 RedisTemplate 来进行操作了。

RedisTemplate操作五种对象

看代码,看代码中的注释:

package com.nowcoder.community;
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.dao.DataAccessException;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class RedisTests {
    @Autowired
    private RedisTemplate redisTemplate;
    // 字符串对象
    @Test
    public void testStrings() {
        String redisKey = "test:count";
        // 插入对应的key和value
        redisTemplate.opsForValue().set(redisKey, 1);
        // 获得对应key的数值
        System.out.println(redisTemplate.opsForValue().get(redisKey));
        // 对应key的数值自增
        System.out.println(redisTemplate.opsForValue().increment(redisKey));
        // 对应key的数值自减
        System.out.println(redisTemplate.opsForValue().decrement(redisKey));
    }
    // Hash对象
    @Test
    public void testHashes() {
        String redisKey = "test:user";
        redisTemplate.opsForHash().put(redisKey, "id", 1);
        redisTemplate.opsForHash().put(redisKey, "username", "zhangsan");
        System.out.println(redisTemplate.opsForHash().get(redisKey, "id"));
        System.out.println(redisTemplate.opsForHash().get(redisKey, "username"));
    }
    // 列表对象
    @Test
    public void testLists() {
        String redisKey = "test:ids";
        // 从左边插入数据
        redisTemplate.opsForList().leftPush(redisKey, 101);
        redisTemplate.opsForList().leftPush(redisKey, 102);
        redisTemplate.opsForList().leftPush(redisKey, 103);
        // 查看当前列表中数据的个数
        System.out.println(redisTemplate.opsForList().size(redisKey));
        // 查看某个索引位置的数据
        System.out.println(redisTemplate.opsForList().index(redisKey, 0));
        // 查看范围区间的数据
        System.out.println(redisTemplate.opsForList().range(redisKey, 0, 2));
        // 从左边弹出,左边leftpop,右边rightpop
        System.out.println(redisTemplate.opsForList().leftPop(redisKey));
        System.out.println(redisTemplate.opsForList().leftPop(redisKey));
        System.out.println(redisTemplate.opsForList().leftPop(redisKey));
    }
    // 集合对象
    @Test
    public void testSets() {
        String redisKey = "test:teachers";
        // 往集合对象中存数据
        redisTemplate.opsForSet().add(redisKey, "刘备", "关羽", "张飞", "赵云", "诸葛亮");
        // 查看集合的大小,有多少数据
        System.out.println(redisTemplate.opsForSet().size(redisKey));
        // 随机弹出一个值
        System.out.println(redisTemplate.opsForSet().pop(redisKey));
        // 查看集合中的所有的数据
        System.out.println(redisTemplate.opsForSet().members(redisKey));
    }
    // 有序集合对象
    @Test
    public void testSortedSets() {
        String redisKey = "test:students";
        // 往有序集合对象中存数据
        redisTemplate.opsForZSet().add(redisKey, "唐僧", 80);
        redisTemplate.opsForZSet().add(redisKey, "悟空", 90);
        redisTemplate.opsForZSet().add(redisKey, "八戒", 50);
        redisTemplate.opsForZSet().add(redisKey, "沙僧", 70);
        redisTemplate.opsForZSet().add(redisKey, "白龙马", 60);
        // 统计数据
        System.out.println(redisTemplate.opsForZSet().zCard(redisKey));
        // 查询某个人的分数
        System.out.println(redisTemplate.opsForZSet().score(redisKey, "八戒"));
        // 查询排名,默认从小到大,reverseRank就是从大到小
        System.out.println(redisTemplate.opsForZSet().reverseRank(redisKey, "八戒"));
        // 查询区间排名数据
        System.out.println(redisTemplate.opsForZSet().reverseRange(redisKey, 0, 2));
    }
    // 删除和设计数据的过期时间
    @Test
    public void testKeys() {
        redisTemplate.delete("test:user");
        System.out.println(redisTemplate.hasKey("test:user"));
        redisTemplate.expire("test:students", 10, TimeUnit.SECONDS);
    }
    // 多次访问同一个key
    @Test
    public void testBoundOperations() {
        String redisKey = "test:count";
        BoundValueOperations operations = redisTemplate.boundValueOps(redisKey);
        operations.increment();
        operations.increment();
        operations.increment();
        operations.increment();
        operations.increment();
        System.out.println(operations.get());
    }
    // Redis编程式事务,并不一定满足我们之前说过的事务,因为不是关系型数据库
    @Test
    public void testTransactional() {
        Object obj = redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String redisKey = "test:tx";
                // 启用事务
                operations.multi();
                operations.opsForSet().add(redisKey, "zhangsan");
                operations.opsForSet().add(redisKey, "lisi");
                operations.opsForSet().add(redisKey, "wangwu");
                System.out.println(operations.opsForSet().members(redisKey));
                // 提交事务
                return operations.exec();
            }
        });
        System.out.println(obj);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值