SpringBoot与Redis多线程入门——多线程redis存取数据

  1. SpringBoot Redis yml 配置

此处省略密码

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    timeout: 3000
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
  1. RedisCofig.java 配置类代码
@EnableCaching
@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.database}")
    private Integer database;
    @Value("${spring.redis.port}")
    private Integer port;

    @Primary
    @Bean(name = "jedisPoolConfig")
    @ConfigurationProperties(prefix = "spring.redis.pool")
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxWaitMillis(10000);
        return jedisPoolConfig;
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setDatabase(database);
        // redisStandaloneConfiguration.setPassword(pwd);
        redisStandaloneConfiguration.setPort(port);
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
        jpcb.poolConfig(jedisPoolConfig);
        JedisClientConfiguration jedisClientConfiguration = jpcb.build();
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }

    /**
     * 配置redisTemplate针对不同key和value场景下不同序列化的方式
     * 此处针对key为String,value为CustomerVo对象的序列化方式
     * @param factory Redis连接工厂
     * @return
     */
    @Primary
    @Bean(name = "customerRedisTemplate")
    public RedisTemplate customerRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
                // 这里是关键,注意替换为自己的类
        Jackson2JsonRedisSerializer redisSerializer = new Jackson2JsonRedisSerializer<>(CustomerVo.class);
        template.setValueSerializer(redisSerializer);
        template.setHashValueSerializer(redisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean(name = "doctorRedisTemplate")
    public RedisTemplate doctorRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        Jackson2JsonRedisSerializer redisSerializer = new Jackson2JsonRedisSerializer<>(DoctorVo.class);
        template.setValueSerializer(redisSerializer);
        template.setHashValueSerializer(redisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}
  1. Vo类和Service类代码

CustomerVo.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CustomerVo {
    private Integer customerId;
    private String queueSeq;
    private String customerName;
    private String customerSex;

    @Override
    public String toString() {
        return "CustomerVo{" +
                "queueSeq='" + queueSeq + '\'' +
                ", customerName='" + customerName + '\'' +
                ", customerSex='" + customerSex + '\'' +
                '}';
    }
}

Service

@Slf4j
@Service
public class RedisLookupService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Async("taskExecutor")
    public CompletableFuture enqueueCustomer(CustomerVo customer) {
        Long result = redisTemplate.opsForList().rightPush("queue", customer);
        log.info("{} 入队..", customer);
        return CompletableFuture.completedFuture(result);
    }

    @Async("taskExecutor")
    public CompletableFuture dequeueCustomer() {
        if (Objects.requireNonNull(redisTemplate.opsForList().size("queue")) < 1) {
            return CompletableFuture.completedFuture(null);
        }
        CustomerVo vo = redisTemplate.opsForList().leftPop("queue");
        log.info("{} 出队...", vo);
        return CompletableFuture.completedFuture(vo);
    }

}

AsyncConfig.java 配置类

因为用到了SpringBoot的多线程,所以要加一下这个配置类

@Configuration
@EnableAsync  // 启用异步任务
public class AsyncConfig {

    // 声明一个线程池(并指定线程池的名字)
    @Bean("taskExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数5:线程池创建时候初始化的线程数
        executor.setCorePoolSize(5);
        //最大线程数5:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(5);
        //缓冲队列500:用来缓冲执行任务的队列
        executor.setQueueCapacity(500);
        //允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        //线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix("RaviAsync-");
        executor.initialize();
        return executor;
    }
}
  1. Controller 测试代码
@Slf4j
@RestController
public class TestController {
    @Autowired
    private RedisLookupService service;

    @GetMapping("/en")
    public String enqueueTry() throws InterruptedException {
        long start = System.currentTimeMillis();
        CustomerVo c1 = new CustomerVo(1, "A031", "马哲", "男");
        CustomerVo c2 = new CustomerVo(2, "A039", "马王", "男");
        CustomerVo c3 = new CustomerVo(3, "A040", "马丽", "女");
        CompletableFuture future1 = service.enqueueCustomer(c1);
        CompletableFuture future2 = service.enqueueCustomer(c3);
        CompletableFuture future3 = service.enqueueCustomer(c2);
        CompletableFuture.allOf(future1, future2, future3).join();
        long end = System.currentTimeMillis();
        log.info("complete test: {}s",(float)(end - start) / 1000);
        return "ok";
    }

    @GetMapping("/qn")
    public String dequeueTry() {
        long start = System.currentTimeMillis();
        CompletableFuture customer1 = service.dequeueCustomer();
        CompletableFuture customer2 = service.dequeueCustomer();
        CompletableFuture customer3 = service.dequeueCustomer();
        CompletableFuture.allOf(customer1, customer2, customer3).join();
        long end = System.currentTimeMillis();
        log.info("complete test: {}s",(float)(end - start) / 1000);
        return "ok";
    }
}

/en的测试结果:
图1

SpringBoot与Redis多线程入门——多线程redis存取数据
图2
SpringBoot与Redis多线程入门——多线程redis存取数据

/qn的测试结果:

SpringBoot与Redis多线程入门——多线程redis存取数据
由此可以发现,多线程已经启动。
  1. 日志设置

yml配置

logging:
  config: classpath:logback.xml
  level:
    com.ravi.mapper: trace

xml配置


            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n

            ${LOG_HOME}/Slf4j_%d{yyyy-MM-dd}.log

            30

            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n

            10MB

参考文章大数据从业者

Original: https://www.cnblogs.com/ceeSomething8/p/15934142.html
Author: cee_nil
Title: SpringBoot与Redis多线程入门——多线程redis存取数据

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/711780/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 【Python手写笔记】 文件与异常,纯肝货

    前言 今天给大家分享一下我自己写的笔记,纯纯的都是干货,关于字好像也能看。这是我学python整理出来的一些资料,希望对大家 有用。想要更多的资料那就的给一个关注了… …

    技术杂谈 2023年6月21日
    093
  • 【源码笔记】ThreadPoolExecutor#runWorker

    /** * Checks if a new worker can be added with respect to current * pool state and the giv…

    技术杂谈 2023年7月24日
    087
  • [转]私有笔记部署

    故事的起源是一个由于线性代数期末考几道计算题卡住算不出来折腾半天而考后看某课代表提前交卷又感觉人均 AK 了以致十分 emo 想要暂时逃避学习的下午。 TL;DR 思源笔记最好。快…

    技术杂谈 2023年5月30日
    0147
  • Aerospike配置

    Aerospike配置 posted on2022-02-09 17:43 duanxz 阅读(66 ) 评论() 编辑 Original: https://www.cnblogs…

    技术杂谈 2023年5月30日
    076
  • 测试驱动开发(TDD)

    测试应用有很多方法,例如,黑盒测试、白盒测试、迭代测试等,然而,这些方法都是从宏观上描述测试的。为了在技术上保障测试的效果,Kent Beck(也是极限编程创始人)提出了在结果上进…

    技术杂谈 2023年5月31日
    0103
  • 为什么方法断点那么慢

    原文一些IDE提供”方法断点”的功能,可以让断点调试看起来非常简洁,然而在调试过程中我们会发现调试反应时间很长,调试器的性能大大降低。在本文中,我会简单解释…

    技术杂谈 2023年6月21日
    0105
  • JAVA8-Lambda-groupingBy

    使用场景: 例:有一群来自五湖四海的大学生,这些学生按照他们的家乡组建一场同乡会。 public static void main(String[] args) { ArrayLi…

    技术杂谈 2023年7月24日
    072
  • MybatisPlus拓展——实现多数据源操作

    多数据源 适用:一般工作时候会有多个数据库,每个库对应不同的业务数据。程序如果每次数据都访问同一个数据库,该数据库压力很大访问会很慢。 1、导入依赖 com.baomidou dy…

    技术杂谈 2023年7月11日
    091
  • 【源码笔记】ThreadPoolExecutor#getTask

    /** * Performs blocking or timed wait for a task, depending on * current configuration set…

    技术杂谈 2023年7月24日
    088
  • 将科学记数法的数字转换为字符串

    我们在从excel里面读取数字或是日期的时候,会碰到一种情况,在excel里面看上去是很正常的一串数字,比如20131114,但是到后台java读出来是2.0131114E7, 我…

    技术杂谈 2023年5月31日
    095
  • 大顶堆MaxHeap(原理与Java实现)

    1. 为什么要引入堆? 1.1 堆的应用场景 有时候我们面临一种实际应用场景需要根据任务的重要程度而划分优先级,对优先级高的任务提供优先服务。 优先级队列(Priority Que…

    技术杂谈 2023年7月23日
    076
  • laravel 定义字符串

    https://learnku.com/docs/laravel/5.6/localization/1376 // &#x5168;&#x666F;&#x9…

    技术杂谈 2023年5月30日
    093
  • [学习笔记]Java正则表达式

    正则表达式 正则表达式定义了字符串的模式,可以用于搜索、编辑或处理文本; 正则表达式使用字符串描述规则,并用于匹配字符串; 一个正则表达式其实就是一个描述规则的字符串,被正则表达式…

    技术杂谈 2023年7月24日
    059
  • 汇编实验二设置栈顶

    实验笔记二:ss设置栈顶 mov ax,2000 mov ss,ax mov sp,0010 mov ax,2000 mov ss,ax mov sp,0010 执行后,内存地址会…

    技术杂谈 2023年6月21日
    077
  • 【转】kubevirt在360的探索之路(k8s接管虚拟化)

    原文:https://blog.51cto.com/u_11451275/4140896?b=totalstatistic apiVersion: v1kind: Persiste…

    技术杂谈 2023年5月30日
    090
  • 袭击Mercurial SCM(HG)

    这个叫水银的源代码管理工具尽管默默无闻,但还是得到了非常多团队的使用。 为了迎合某些团队的须要,我们也要用它来管理我们的代码。 今天的任务是先袭击学习。磨刀不误砍柴工。 对工具的掌…

    技术杂谈 2023年5月31日
    0102
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球