Redis(连接池)

news2024/10/7 20:36:33

SpringBoor环境下使用redis连接池

依赖:

<dependencies>
        <dependency>
            <groupId>com.yugabyte</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0-yb-11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

测试类:“

package com.pb;

public class RedisTest1 {

    @Test
    public  void  test(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();   //创建连接池的配置对象
        jedisPoolConfig.setMaxTotal(100);    //并发量在100左右
        jedisPoolConfig.setMaxIdle(50);  //最大的等待连接
        jedisPoolConfig.setMinIdle(10);  //最小的等待连接
        jedisPoolConfig.setTestOnBorrow(false);   //其作用是设置在从连接池中获取连接时,是否检测并确保获取的连接可用。
        jedisPoolConfig.setTestOnReturn(false);   //用于设置在将连接还回连接池时是否检测连接的可用性
        jedisPoolConfig.setTestOnCreate(true);   //用于设置在创建新的连接时是否检测连接的可用性
        jedisPoolConfig.setBlockWhenExhausted(true);    //用于设置当连接池中的连接耗尽时,是阻塞等待还是立即抛出异常。

        jedisPoolConfig.setMaxWaitMillis(1000);  //等待1s

        //创建连接池
        JedisPool jedisPool=new JedisPool(jedisPoolConfig,"192.168.200.166",6380,2000,"123.com");

        Jedis jedis=null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(10);
            jedis.set("curry","库里");
            String curry = jedis.get("curry");
            System.out.println(curry);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();  //关闭连接
        }

    }
}

Spring—Redis(连接池)

pom

<dependencies>
        <dependency>
            <groupId>com.yugabyte</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0-yb-11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.0.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
    </dependencies>

配置文件

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean  id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="100"/>
        <property name="maxIdle" value="50"/>
        <property name="minIdle" value="10"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="testOnCreate" value="false"/>
    </bean>

    <bean  id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:usePool="true" p:poolConfig-ref="jedisPoolConfig"
          p:hostName="192.168.200.166" p:port="6380" p:database="10"
          p:password="123.com" p:timeout="200000">
    </bean>

    <bean class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="connectionFactory">

       
    </bean>

</beans>

测试:

package com.pb;


@RunWith(value = SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations ={"classpath:beans.xml"})
public class RedisTest1 {

    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public  void  test(){
        //System.out.println(redisTemplate);

        //操作Spring类型
        redisTemplate.opsForValue().set("aa","aa");

        String aa = (String) redisTemplate.opsForValue().get("aa");
        System.out.println(aa);

    }
}

但是出现了一个问题  就是乱码问题

需要在xml中  内部Bean

<bean class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="connectionFactory">

        <!--创建一个内部Bean-->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>

        <!--创建一个内部Bean-->
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
    </bean>

但是这样子又出现一个问题 就是  保存对象的额时候出现的问题   可能还会出现乱码

/**
     * 存对象
     */
    @Test
    public void  test2(){

        User user = new User();
        user.setId(1);
        user.setName("curry");
        user.setSex("男");

        redisTemplate.opsForValue().set("user:1:info",user);

        User user1 = (User) redisTemplate.opsForValue().get("user:1:info");
        System.out.println(user1);

    }

上面的代码会报错  纯是编码问题:   

我们就需要在xml 中配置:

  <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
 </property>

 还有一个和就是可能会保存hash数据

  <!--创建一个内部Bean-->
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>

        <!--创建一个内部Bean-->
        <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>

 测试:

 /**
     * 存hash
     */
    @Test
    public  void  test3(){
        Map<String, Object> map=new HashMap<>();
        User user = new User();
        user.setId(1);
        user.setName("curry");
        user.setSex("男");
        map.put("user11",user);
        redisTemplate.opsForHash().putAll("user:1:hash",map);


        User user11 = (User) redisTemplate.opsForHash().get("user:1:hash", "user11");

        System.out.println(user11);
    }
}

Spring—Boot声明式缓存

SpringBoot_data_redis

依赖:(boot版本   2.6.13)

<dependencies>
        <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

配置文件  application.yml

spring:
  redis:
    host: 192.168.200.166
    port: 6380
    password: 123.com
    connect-timeout: 10000

    jedis:
      pool:
        max-active: 100
        max-idle: 50
        min-idle: 10
        max-wait: 1000
    database: 10

测试类:

package com.pb;


@SpringBootTest
class SpringBootDataRedisApplicationTests {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        System.out.println(redisTemplate);

        redisTemplate.opsForValue().set("java","opoo");
        String java = stringRedisTemplate.opsForValue().get("java");
        System.out.println(java);


        User user = new User(1001,"curry","男");

        redisTemplate.opsForValue().set("123123",user);
    }

}

不管是村对象还是存单个值 都有乱码问题  

我们需要写一个配置类

package com.pb.com.config;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){

        RedisTemplate redisTemplate = new RedisTemplate();

        redisTemplate.setConnectionFactory(connectionFactory);

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.afterPropertiesSet();
        return  redisTemplate;
    }
}

在测试 就没有乱码了

过期时间:

@Test
    void  test(){
        redisTemplate.opsForValue().set("java","hello",5000, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("spring","spring", Duration.ofSeconds(5000));
    }

List集合:

 @Test
    void  test(){
        redisTemplate.opsForList().rightPushAll("user:1:info","11","22","33","44","55");

        List range = redisTemplate.opsForList().range("user:1:info", 0, -1);
        System.out.println(range);
    }

Hash

 @Test
    void  test2(){
        Map<String,Object> map=new HashMap<>();
        map.put("id",1001);
        map.put("name","詹姆斯");
        map.put("sex","男");

       redisTemplate.opsForHash().putAll("user:info",map);

       Map<Object,Object> entries=redisTemplate.opsForHash().entries("user:info");
       Iterator<Map.Entry<Object, Object>> integer=entries.entrySet().iterator();
       while (integer.hasNext()){
           Map.Entry<Object,Object>  next= integer.next();
           System.out.println(next.getKey()+"\t"+next.getValue());
       }

        Set<Object> keys = redisTemplate.opsForHash().keys("user:info");
        for (Object key : keys) {
            Object o = redisTemplate.opsForHash().get("user:info", key);
            System.out.println(o);

        }
    }

其他的操作   (匿名函数)

 @Test
    public  void test3(){
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushAll();
                return null;
            }
        });
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/502449.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

乘势而上,在社科大能源管理硕士项目的引领下,更上一层楼

很多人都说&#xff0c;生活的起点不重要&#xff0c;重要的是你最后抵达到哪里。进入职场的门槛后&#xff0c;我们一路过关打怪才拥有了如今的职位。在享受喜悦的同时&#xff0c;有为未来做规划吗&#xff0c;乘势而上才是明智的抉择&#xff0c;让我们在社科大能源管理硕士…

Seata 1.6.1整合SpringCloud实现分布式事务(含代码)

一、环境: seata 1.6.1spring cloud :2021.0.6spring cloud alibaba: 2021.0.4.0nacos: 2.2.1mysql: 8二、部署seata-server 2.1 启动nacos 这里不再赘述 2.2 下载seata-server 下载地址:https://seata.io/zh-cn/blog/download.html 下载后解压,即为seata-server端,提…

摄影测量-笔记(理解篇)

1、基本原理 基于测量中的前方交会原理。 在两个已知点上分别拍摄一张影像&#xff0c;通过人眼观测&#xff08;一只眼睛观察一张影像上的同名点a1和a2&#xff09;&#xff0c;就能得出空间对应点A的坐标。空间景物通过传感器构像&#xff0c;再用人眼观察构像的像片产生生…

GPT 学术优化版使用指南 -- GPT Academic

目录 1. 项目介绍 1.1 简介 1.2 功能说明 2. 环境配置 2.1 本地安装

STL-String容器

string本质上是一个类&#xff0c;string 类内部封装了很多成员方法 例如&#xff1a;查找find&#xff0c;拷贝copy&#xff0c;删除delete 替换replace&#xff0c;插入insert string管理char*所分配的内存&#xff0c;不用担心复制越界和取值越界等&#xff0c;由类内部进…

C++容器适配器stack和queue(含deque,priority_queue)

目录 1.容器适配器 1.1 什么是适配器 1.2 STL标准库中stack和queue底层结构 1.3 deque 1.3.1 deque原理介绍&#xff08;了解&#xff09; 1.3.2 deque优点和缺点 1.3.3 为什么选择deque作为stack和queue的底层默认容器 2. stack介绍和使用 2.1 stack介绍 2.2 stack使用 2.3 …

HTML处理控件Aspose.Html 功能演示:在 C# 中将 HTML 转换为 JPG

Aspose.Html for .NET 是一种高级的HTML操作API&#xff0c;可让您直接在.NET应用程序中执行广泛的HTML操作任务&#xff0c;Aspose.Html for .NET允许创建&#xff0c;加载&#xff0c;编辑或转换&#xff08;X&#xff09;HTML文档&#xff0c;而无需额外的软件或工具。API还…

swing基本组件用法_JTooBar

Swing提供了JTooBar类来创建工具条&#xff0c;并且可以往JTooBar中添加多个工具按钮 JToolBar API: 方法名称方法功能JToolBar(String name,int orientation)创建一个名为name&#xff0c;方向为orientation的工具条对象&#xff0c;其orientation的是取值可以是SwingConsta…

MySQL基础(九)子查询

子查询指一个查询语句嵌套在另一个查询语句内部的查询&#xff0c;这个特性从MySQL 4.1开始引入。 SQL 中子查询的使用大大增强了 SELECT 查询的能力&#xff0c;因为很多时候查询需要从结果集中获取数据&#xff0c;或者需要从同一个表中先计算得出一个数据结果&#xff0c;然…

单调队列解决滑动窗口问题

文章目录 单调队列结构解决滑动窗口问题什么是单调队列&#xff1f;[239. 滑动窗口最大值](https://leetcode.cn/problems/sliding-window-maximum/)单调队列框架滑动窗口解题框架完整的解题代码如下&#xff1a;我的实现&#xff1a; 单调队列结构解决滑动窗口问题 什么是单调…

CVE-2023-27524 Apache Superset Auth Bypass|附检测工具

漏洞描述 Apache Superset是一个开源数据可视化和探索工具。Apache Superset 版本&#xff08;包括 2.0.1&#xff09;中的会话验证攻击。没有根据安装说明更改默认配置的SECRET_KEY的安装允许攻击者验证和访问未经授权的资源。这不会影响更改了SECRET_KEY配置默认值的Superse…

JAVA快速开发框架 一键生成表单模板代码

从计算机诞生开始&#xff0c;虽然编程的形式随着硬件及软件的不断进步而不停迭代&#xff0c;但是从事计算机技术行业的人员始终与编写代码的任务紧密联系在一起。因此如何提高软件开发的效率和质量&#xff0c;一直是软件工程领域的重要问题之一。 这一方面是由于在不同软件…

MQ(面试问题简析)学习笔记

文章目录 1. 为什么使用消息队列2. 消息队列有什么优缺点3. Kafka、ActiveMQ、RabbitMQ、RocketMQ 有什么优缺点&#xff1f;4. 如何保证消息队列的高可用4.1 RabbitMQ 的高可用性4.2 Kafka 的高可用性 5. 如何保证消息不被重复消费&#xff08;如何保证消息消费的幂等性&#…

1、Cloudsim和Workflowsim仿真环境下载

1、WorkflowSim的下载和安装 workflowsim下载地址 2、Cloudsim的下载和安装 cloudsim官网 cloudsim4.0安装包地址 2、Cloudsim如何工作 Cloudsim如何工作&#xff1f;原版内容 cloudsim配置 下面这是CloudsimExamples1的代码&#xff1a; package org.cloudbus.…

论文导读 | 大语言模型上的精调策略

随着预训练语言模型规模的快速增长&#xff0c;在下游任务上精调模型的成本也随之快速增加。这种成本主要体现在两方面上&#xff1a;一&#xff0c;计算开销。以大语言模型作为基座&#xff0c;精调的显存占用和时间成本都成倍增加。随着模型规模扩大到10B以上&#xff0c;几乎…

SpringBoot启用web模拟测试(一)

添加依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.5.10</version> </dependency> 模拟端口 虚拟请求测试 Slf4j RestController RequestMappin…

java后端面试大全,java后端面试宝典

JAVA_LEARNING_CONTENT JAVA后端面试大全&#xff0c;java后端面试宝典 一个分布式锁的解决方案&#xff0c;另一个是分布式事务的解决方案 -2 flink 链接&#xff1a;flink参考文章 -1 linux of view 参考链接&#xff1a; linux常见面试题 linux查看占用cup最高的10个进…

机电设备故障ar远程维修软件缩短生产线中断时间

电机属于工业生产中的关键设备之一&#xff0c;处于长期运转阶段&#xff0c;因此电机容易出现故障&#xff0c;极易增加企业生产成本&#xff0c;影响生产计划。引进AR远程维修技术效果显著。 AR远程维修技术是一种将虚拟信息与实际场景相结合的技术。当电机出现故障时&#x…

基于AT89C51单片机的交通灯设计与仿真

点击链接获取Keil源码与Project Backups仿真图&#xff1a; https://download.csdn.net/download/qq_64505944/87763760?spm1001.2014.3001.5503 源码获取 主要内容&#xff1a; 设计一个能够控制十二盏交通信号灯的模拟系统,:利用单片机的定时器定时&#xff0c;令十字路口…