首页 > 数据库 >Spring整合Redis(十八)

Spring整合Redis(十八)

时间:2022-09-01 21:35:01浏览次数:55  
标签:operations Spring 十八 Redis System redisKey println redisTemplate out

一、Redis简介

  • Redis是一款基于键值对的NoSQL数据库,它的值支持多种数据结构:
    字符串(strings)、哈希(hashes)、列表(lists)、集合(sets)、有序集合(sorted sets)等。
  • Redis将所有的数据都存放在内存中,所以它的读写性能十分惊人。
    同时,Redis还可以将内存中的数据以快照或日志的形式保存到硬盘上,以保证数据的安全性。
  • Redis典型的应用场景包括:缓存、排行榜、计数器、社交网络、消息队列等。

二、引入依赖

pom.xml

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

三、配置Redis

1.配置数据库参数

application.yml

spring:
  redis:
    database: 11 #选择数据库
    host: localhost #ip
    port: 6379  # 端口

2.编写配置类,构造RedisTemplate

将key的类型设置为String,并指定序列化的方式。

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置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;
    }

}

3.示例

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.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;

@SpringBootTest
public class RedisTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testStrings() {
        String redisKey = "test:count";
        // 存String
        redisTemplate.opsForValue().set(redisKey, 1);
        // 取String
        System.out.println(redisTemplate.opsForValue().get(redisKey)); // 1
        // 自增
        System.out.println(redisTemplate.opsForValue().increment(redisKey)); // 2
        // 自减
        System.out.println(redisTemplate.opsForValue().decrement(redisKey)); // 1
    }

    @Test
    public void testHashes() {
        String redisKey = "test:user";
        // 存hash
        redisTemplate.opsForHash().put(redisKey, "id", 1);
        redisTemplate.opsForHash().put(redisKey, "username", "zhangsan");
        // 取hash
        System.out.println(redisTemplate.opsForHash().get(redisKey, "id")); // 1
        System.out.println(redisTemplate.opsForHash().get(redisKey, "username")); // zhangsan
    }

    @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)); // 3
        // 获取索引处的数据
        System.out.println(redisTemplate.opsForList().index(redisKey, 0)); // 103
        // 获取范围内的数据
        System.out.println(redisTemplate.opsForList().range(redisKey, 0, 2)); // [103, 102, 101]

        // 从左边弹出数据
        System.out.println(redisTemplate.opsForList().leftPop(redisKey)); // 103
        System.out.println(redisTemplate.opsForList().leftPop(redisKey)); // 102
        System.out.println(redisTemplate.opsForList().leftPop(redisKey)); // 101
    }

    @Test
    public void testSets() {
        String redisKey = "test:teachers";
        // 将值存入集合
        redisTemplate.opsForSet().add(redisKey, "刘备", "关羽", "张飞", "赵云", "诸葛亮");

        // 值个数
        System.out.println(redisTemplate.opsForSet().size(redisKey)); // 5
        // 随机弹出一个值
        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)); // 5
        // 某个值的分数
        System.out.println(redisTemplate.opsForZSet().score(redisKey, "八戒")); // 50.0
        // 某个值的排名(倒序,大到小)
        System.out.println(redisTemplate.opsForZSet().reverseRank(redisKey, "八戒")); //4
        // 某个排名范围的数据(倒序)
        System.out.println(redisTemplate.opsForZSet().reverseRange(redisKey, 0, 2)); //[悟空, 唐僧, 沙僧]
    }

    @Test
    public void testKeys() {
        // 删除key
        redisTemplate.delete("test:user");
        System.out.println(redisTemplate.hasKey("test:user")); // false

        // 设置过期时间
        redisTemplate.expire("test:students", 10, TimeUnit.SECONDS);
    }

    // 多次访问同一个key
    @Test
    public void testBoundOperations() {
        String redisKey = "test:count";
        // 其他数据类型也有类似的绑定方法,不用每次操作都传入key
        BoundValueOperations operations = redisTemplate.boundValueOps(redisKey);
        operations.increment();
        operations.increment();
        operations.increment();
        operations.increment();
        operations.increment();
        System.out.println(operations.get());
    }

    // 编程式事务
    @Test
    public void testTransactional() {
        // redis事务是将一批操作一块发送给服务器执行的的,
        // 所以事务内的操作不会立刻执行,因此在事务中不要查询
        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); // [1, 1, 1, [wangwu, lisi, zhangsan]]
    }

}

标签:operations,Spring,十八,Redis,System,redisKey,println,redisTemplate,out
From: https://www.cnblogs.com/dalelee/p/16647284.html

相关文章

  • SpringBoot简单使用(2)
    1.2.7:CommandLineRunner接口:开发中可能会有这样的情景。需要在容器启动后执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我......
  • SpringMVC 03: 请求和响应的乱码解决 + SpringMVC响应Ajax请求
    请求或响应的中文乱码问题tomcat9解决了get请求和响应的中文乱码问题,但是没有解决post请求或响应的中文乱码问题tomcat10解决了get和post请求以及响应的中文乱码问题......
  • Springboot整合Sentinel实现流控
    在Springboot项目中整合Sentinel实现流控,Gateway整合Sentinel见Gateway整合Sentinel,Sentinel-daahboard的改造见Sentinel-dashboard改造(普通流控和网关流控规则持久化到Nac......
  • Redis使用 Redis封装
    封装Redis:一、application.properties:#过期日期:10800秒(3分钟)PitND.expire.pro=10800二、MainEventHERDMRedis.java:importorg.springframework.beans.facto......
  • Spring(四)-声明式事务
    Spring-04声明式事务1、事务的定义事务就是由一组逻辑上紧密关联的多个工作单元(数据库操作)而合并成一个整体,这些操作要么都执行,要么都不执行。2、事务的特性:ACID1)原子......
  • SpringBoot上传文件
    前端使用ElementUI+Vue后端使用SpringBoot1前端代码1.0组件导入&初始化导入ElementUI、Axios、Vue的资源。完成Vue的初始化和生效区域的设置。这些资源都能找到,把......
  • 【Azure Redis 缓存】Azure Redis 功能性讨论三: 调优参数配置
    问题描述在使用AzureRedis的服务中,遇见了以下系列问题需要澄清:在开源Redis6.0中,多线程默认禁用,只使用主线程。如需开启需要修改redis.config配置文件。Redis的多线......
  • Redis 管理工具 - Redis Desktop Manager
     RedisDesktopManager可以轻松管理Redis桌面。为您提供了一个易于使用的GUI,可以访问您的Redis数据库并执行一些基本操作:将键视为树,CRUD键,通过shell执行命令。RESP.app......
  • 【Spring Boot】Spring 最常用的 7 大类注解,史上最强整理!
    原文:https://mp.weixin.qq.com/s/q7hVf1VluD8vPs7srRU2dA 随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍......
  • SpringMVC视图
    SpringMVC中的视图SpringMVC中的视图是view接口,视图的作用是用来渲染数据,将模型model中的数据展示给用户,SpringMVC视图的种类很多,默认有转发视图:InternalResourceView和重......