springboot整合spring-data-redis使用redisTemplate操作

2024-05-29 08:32

本文主要是介绍springboot整合spring-data-redis使用redisTemplate操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一.spring data redis的安装

1.1 安装gcc

安装命令为:yum install gcc-c++

[root@bogon ~]# yum install gcc-c++
Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos,: subscription-managerThis system is not registered with an entitlement server. You can use subscription-manager to register.Loading mirror speeds from cached hostfile* base: ftp.sjtu.edu.cn* extras: ftp.sjtu.edu.cn* updates: mirror.lzu.edu.cn
base                                                     | 3.6 kB     00:00     
extras                                                   | 2.9 kB     00:00     
updates                                                  | 2.9 kB     00:00     
(1/2): extras/7/x86_64/primary_db                          | 225 kB   00:00     
(2/2): updates/7/x86_64/primary_db                         | 5.7 MB   00:02    
Installed:gcc-c++.x86_64 0:4.8.5-44.el7                                                                                                                                                        Dependency Installed:cpp.x86_64 0:4.8.5-44.el7                            gcc.x86_64 0:4.8.5-44.el7           glibc-devel.x86_64 0:2.17-323.el7_9           glibc-headers.x86_64 0:2.17-323.el7_9        kernel-headers.x86_64 0:3.10.0-1160.15.2.el7         libmpc.x86_64 0:1.0.1-3.el7         libstdc++-devel.x86_64 0:4.8.5-44.el7        Dependency Updated:glibc.x86_64 0:2.17-323.el7_9     glibc-common.x86_64 0:2.17-323.el7_9     libgcc.x86_64 0:4.8.5-44.el7     libgomp.x86_64 0:4.8.5-44.el7     libstdc++.x86_64 0:4.8.5-44.el7    Complete!

#查看gcc的版本:gcc -v

[root@bogon ~]# gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 

1.2 解压redis的软件包

进入redis的存储目录:/bonc-kecheng-jingxiang ,进行解压

[root@bogon bonc-kecheng-jingxiang]# tar -zxvf redis-6.2.1.tar.gz 
redis-6.2.1/
redis-6.2.1/.github/
redis-6.2.1/.github/ISSUE_TEMPLATE/
redis-6.2.1/.github/ISSUE_TEMPLATE/bug_report.md
redis-6.2.1/.github/ISSUE_TEMPLATE/crash_report.md
redis-6.2.1/.github/ISSUE_TEMPLATE/feature_request.md
redis-6.2.1/.github/ISSUE_TEMPLATE/other_stuff.md
redis-6.2.1/.github/ISSUE_TEMPLATE/question.md
redis-6.2.1/.github/workflows/
redis-6.2.1/.github/workflows/ci.yml
redis-6.2.1/.github/workflows/daily.yml
redis-6.2.1/.gitignore
redis-6.2.1/00-RELEASENOTES
redis-6.2.1/BUGS
redis-6.2.1/CONDUCT
redis-6.2.1/CONTRIBUTING
redis-6.2.1/COPYING
redis-6.2.1/INSTALL
redis-6.2.1/MANIFESTO
redis-6.2.1/Makefile
redis-6.2.1/README.md

1.3 进入解压后的目录进行编译

进入redis的解压后的目录,然后执行:make PREFIX=/usr/local/redis install  进行编译

[root@bogon bonc-kecheng-jingxiang]# ls
1.txt  redis-6.2.1  redis-6.2.1.tar.gz  xfce-tools-base.tar
[root@bogon bonc-kecheng-jingxiang]# cd redis-6.2.1/
[root@bogon redis-6.2.1]# ls
00-RELEASENOTES  CONDUCT       COPYING  INSTALL   MANIFESTO  redis.conf  runtest-cluster    runtest-sentinel  src    TLS.md
BUGS             CONTRIBUTING  deps     Makefile  README.md  runtest     runtest-moduleapi  sentinel.conf     tests  utils
[root@bogon redis-6.2.1]# pwd
/bonc-kecheng-jingxiang/redis-6.2.1
[root@bogon redis-6.2.1]# make PREFIX=/usr/local/redis install
cd src && make install
make[1]: Entering directory `/bonc-kecheng-jingxiang/redis-6.2.1/src'CC Makefile.dep
make[1]: Leaving directory `/bonc-kecheng-jingxiang/redis-6.2.1/src'
make[1]: Entering directory `/bonc-kecheng-jingxiang/redis-6.2.1/src'
rm -rf redis-server redis-sentinel redis-cli redis-benchmark redis-check-rdb redis-check-aof *.o *.gcda *.gcno *.gcov redis.info lcov-html Makefile.dep dict-benchmark
rm -f adlist.d quicklist.d ae.d anet.d dict.d server.d sds.d zmalloc.d lzf_c.d lzf_d.d pqsort.d zipmap.d sha1.d ziplist.d release.d networking.d util.d object.d db.d replication.d rdb.d t_string.d t_list.d t_set.d t_zset.d t_hash.d config.d aof.d pubsub.d multi.d debug.d sort.d intset.d syncio.d cluster.d crc16.d endianconv.d slowlog.d scripting.d bio.d rio.d rand.d memtest.d crcspeed.d crc64.d bitops.d sentinel.d notify.d setproctitle.d blocked.d hyperloglog.d latency.d sparkline.d redis-check-rdb.d redis-check-aof.d geo.d lazyfree.d module.d evict.d expire.d geohash.d geohash_helper.d childinfo.d defrag.d siphash.d rax.d t_stream.d listpack.d localtime.d lolwut.d lolwut5.d lolwut6.d acl.d gopher.d tracking.d connection.d tls.d sha256.d timeout.d setcpuaffinity.d monotonic.d mt19937-64.d anet.d adlist.d dict.d redis-cli.d zmalloc.d release.d ae.d crcspeed.d crc64.d siphash.d crc16.d monotonic.d cli_common.d mt19937-64.d ae.d anet.d redis-bench

 

1.4  启动redis

1.修改一下配置redis.conf配置文件的内容:

先进入到 redis-6.2.1目录下

[root@localhost redis-6.2.1]# vi redis.conf
[root@localhost redis-6.2.1]# 

修改内容如下:

2.先进入到:/usr/local/redis/bin 这个目录下,然后执行启动脚本命令:

 ./redis-server  /bonc-kecheng-jingxiang/redis-6.2.1/redis.conf

root@bogon redis-6.2.1]# cd /usr/local
[root@bogon local]# ls
bin  etc  games  include  lib  lib64  libexec  redis  sbin  share  src
[root@bogon local]# cd redis
[root@bogon redis]# ls
bin
[root@bogon redis]# cd bin
[root@bogon bin]# ls
redis-benchmark  redis-check-aof  redis-check-rdb  redis-cli  redis-sentinel  redis-server
[root@bogon bin]# ./redis-server  /bonc-kecheng-jingxiang/redis-6.2.1/redis.conf
9723:C 14 Mar 2021 21:52:47.279 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
9723:C 14 Mar 2021 21:52:47.280 # Redis version=6.2.1, bits=64, commit=00000000, modified=0, pid=9723, just started
9723:C 14 Mar 2021 21:52:47.280 # Configuration loaded
9723:M 14 Mar 2021 21:52:47.280 * Increased maximum number of open files to 10032 (it was originally set to 1024).
9723:M 14 Mar 2021 21:52:47.280 * monotonic clock: POSIX clock_gettime_._                                                  _.-``__ ''-._                                             _.-``    `.  `_.  ''-._           Redis 6.2.1 (00000000/0) 64 bit.-`` .-```.  ```\/    _.,_ ''-._                                   (    '      ,       .-`  | `,    )     Running in standalone mode|`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379|    `-._   `._    /     _.-'    |     PID: 9723`-._    `-._  `-./  _.-'    _.-'                                   |`-._`-._    `-.__.-'    _.-'_.-'|                                  |    `-._`-._        _.-'_.-'    |           http://redis.io        `-._    `-._`-.__.-'_.-'    _.-'                                   |`-._`-._    `-.__.-'    _.-'_.-'|                                  |    `-._`-._        _.-'_.-'    |                                  `-._    `-._`-.__.-'_.-'    _.-'                                   `-._    `-.__.-'    _.-'                                       `-._        _.-'                                           `-.__.-'                                               9723:M 14 Mar 2021 21:52:47.281 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
9723:M 14 Mar 2021 21:52:47.281 # Server initialized
9723:M 14 Mar 2021 21:52:47.281 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
9723:M 14 Mar 2021 21:52:47.282 * Loading RDB produced by version 6.2.1
9723:M 14 Mar 2021 21:52:47.282 * RDB age 51 seconds
9723:M 14 Mar 2021 21:52:47.282 * RDB memory usage when created 0.77 Mb
9723:M 14 Mar 2021 21:52:47.282 * DB loaded from disk: 0.000 seconds
9723:M 14 Mar 2021 21:52:47.282 * Ready to accept connections

启动后的截图: 

1.5 启动客户端进行查看

同样在打开一个新窗口,先进到/usr/local/redis/bin目录下,然后给执行: ./redis-cli

[root@192 ~]# cd /usr/local/redis
[root@192 redis]# bin
bash: bin: command not found...
[root@192 redis]# ls
bin
[root@192 redis]# cd bin
[root@192 bin]# ls
dump.rdb         redis-check-aof  redis-cli       redis-server
redis-benchmark  redis-check-rdb  redis-sentinel
[root@192 bin]# ./redis-cli
127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> 

二 springboot整合spring data redis

2.1  spring data redis的作用

spring data redis的作用是简化对redis的开发工作,属于spring data 下的一个模块。

工程结构:

 2.2 pom文件

<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.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency>

2.3 application配置文件

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

2.4 redis连接池

package com.ljf.spring.boot.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** 完成对Redis的整合的一些配置***/
@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);// 使用Jackson2JsonRedisSerialize 替换默认序列化Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper = new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objectMapper);// 设置value的序列化规则和 key的序列化规则redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;}
}

2.5 controller

package com.ljf.spring.boot.demo.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** @ClassName: RedisController* @Description: TODO* @Author: liujianfu* @Date: 2021/03/14 20:59:26 * @Version: V1.0**/
@Controller
public class RedisController {@Autowiredprivate StringRedisTemplate stringRedisTemplate;@Autowiredprivate RedisTemplate redisTemplate;/*** 添加一个字符串*/@RequestMapping("/add")@ResponseBodypublic String testSet(){this.redisTemplate.opsForValue().set("key", "中国人民ruc");System.out.println("add=====");return "ok";}/*** 获取一个字符串*/@RequestMapping("/get")@ResponseBodypublic String testGet(){String value = (String)this.redisTemplate.opsForValue().get("key");System.out.println(value);return  value;}
}

2.6 启动访问

2. 新增

3.查询

这篇关于springboot整合spring-data-redis使用redisTemplate操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1013156

相关文章

Python调用Orator ORM进行数据库操作

《Python调用OratorORM进行数据库操作》OratorORM是一个功能丰富且灵活的PythonORM库,旨在简化数据库操作,它支持多种数据库并提供了简洁且直观的API,下面我们就... 目录Orator ORM 主要特点安装使用示例总结Orator ORM 是一个功能丰富且灵活的 python O

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程