java连接redis是数据库(redis在java项目中的使用)

操作系统:CentOS-7.8 Redis版本:6.0.5 SpringBoot 2.1.5.RELEASE Java Version 1.8.0_231

一、使用Redis客户端

Jedis、Redisson和Lettuce都是比较常用的支持连接Redis的客户端,所以在这里我们主要演示这三种客户端如何连接不同的redis模式的redis
java连接redis是数据库(redis在java项目中的使用)

1.JedisJedis特点

比较经典的Redis的Java客户端,对Redis的命令支持比较全面

比较轻量和简洁,对其进行改造和集成比较方便

不支持异步,方法调用都是同步的,使用的阻塞IO

客户端实例非线程安全,多线程并发场景下,需要通过连接池来使用客户端

早期版本Spring的默认客户端

使用演示

pom依赖

1<dependency>2<groupId>redis.clients</groupId>3<artifactId>jedis</artifactId>4<version>2.9.3</version>5</dependency>

Jedis连接单机单实例Redis

Jedis连接哨兵模式Redis

1importredis.clients.jedis.Jedis; 2importredis.clients.jedis.JedisPoolConfig; 3importredis.clients.jedis.JedisSentinelPool; 4 5importjava.util.Set; 6 7/** 8*@author爱做梦的锤子 9*@create2020/7/1710*/11publicclassSentinelJedis{1213privateJedisSentinelPooljedisSentinelPool;1415/**16*连接哨兵模式的redis17*18*@parammasterNameredis的master名称19*@paramsentinels哨兵的主机和端口信息20*@parampasswordredis的认证密码21*/22publicSentinelJedis(StringmasterName,Set<String>sentinels,Stringpassword){23//根据redis的信息创建一个redis哨兵的连接池24JedisPoolConfigconfig=newJedisPoolConfig();25config.setMaxTotal(10);26config.setMaxIdle(5);27config.setMinIdle(5);28jedisSentinelPool=newJedisSentinelPool(masterName,sentinels,config,password);29}3031/**32*从连接池中取出一个客户端33*34*@return获取一个Jedis客户端35*/36publicJedisconnect(){37returnjedisSentinelPool.getResource();38}3940/**41*销毁连接池42*/43publicvoidclose(){44jedisSentinelPool.close();45jedisSentinelPool.destroy();46}47}

Jedis连接集群模式Redis

1importorg.apache.commons.pool2.impl.GenericObjectPoolConfig; 2importredis.clients.jedis.HostAndPort; 3importredis.clients.jedis.JedisCluster; 4 5importjava.util.Set; 6 7/** 8*@author爱做梦的锤子 9*@create2020/7/1710*/11publicclassClusterJedis{1213privateSet<HostAndPort>redisNodes;14privateStringpassword;15privateGenericObjectPoolConfigconfig;1617/**18*连接rediscluster19*20*@paramredisNodes集群中redis节点信息21*@parampasswordredis密码22*/23publicClusterJedis(Set<HostAndPort>redisNodes,Stringpassword){24this.redisNodes=redisNodes;25this.password=password;26config=newGenericObjectPoolConfig();27config.setMaxTotal(10);28config.setMaxIdle(5);29config.setMinIdle(5);30}3132/**33*连接rediscluster34*35*@return一个rediscluster客户端36*/37publicJedisClusterconnect(){38JedisClusterjedisCluster=newJedisCluster(redisNodes,10000,10000,3,password,config);39returnjedisCluster;40}4142}

以上三段代码是使用Jedis连接三种模式下Redis的简易演示代码,下面再附上测试类代码

测试类

1/** 2*@author爱做梦的锤子 3*@create2020/7/17 4*/ 5 6publicclassJedisTest{ 7 8privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(JedisTest.class); 9privatestaticfinalStringTEST_KEY=”jedis”;10privatestaticfinalStringTEST_VALUE=”dream-hammer”;1112@Test13publicvoidsingleInstance(){14SingleInstanceJedissingleInstanceJedis=newSingleInstanceJedis(“192.168.56.90″,6379,”123456”);15Jedisjedis=singleInstanceJedis.connect();16jedis.set(TEST_KEY,TEST_VALUE);17LOGGER.info(“jedis单机单实例:{}”,jedis.get(TEST_KEY));18Assert.assertEquals(TEST_VALUE,jedis.get(TEST_KEY));19}2021@Test22publicvoidsentinel(){23Set<String>sentinels=newHashSet<>();24sentinels.add(“192.168.56.91:26379”);25sentinels.add(“192.168.56.92:26379”);26sentinels.add(“192.168.56.93:26379”);27SentinelJedissentinelJedis=newSentinelJedis(“redis-master”,sentinels,”123456″);28Jedisjedis=sentinelJedis.connect();29jedis.set(TEST_KEY,TEST_VALUE);30LOGGER.info(“jedis哨兵模式:{}”,jedis.get(TEST_KEY));31Assert.assertEquals(TEST_VALUE,jedis.get(TEST_KEY));32}3334@Test35publicvoidcluster(){36Set<HostAndPort>redisNodes=newHashSet<>();37redisNodes.add(newHostAndPort(“192.168.56.81”,6379));38redisNodes.add(newHostAndPort(“192.168.56.82”,6379));39redisNodes.add(newHostAndPort(“192.168.56.83”,6379));40redisNodes.add(newHostAndPort(“192.168.56.84”,6379));41redisNodes.add(newHostAndPort(“192.168.56.85”,6379));42redisNodes.add(newHostAndPort(“192.168.56.86″,6379));43ClusterJedisclusterJedis=newClusterJedis(redisNodes,”123456”);44JedisClusterjedisCluster=clusterJedis.connect();45jedisCluster.set(TEST_KEY,TEST_VALUE);46LOGGER.info(“jedis集群模式:{}”,jedisCluster.get(TEST_KEY));47Assert.assertEquals(TEST_VALUE,jedisCluster.get(TEST_KEY));48}49}2.RedissonRedisson特点

基于Netty实现,使用非阻塞IO,支持异步,性能高

API是线程安全的,可以操作单个Redisson连接来完成多种操作

实现多种分布式和可扩展的Java数据结构,例如,分布式锁,分布式集合,可通过Redis支持延迟队列

Redisson注重分布式和锁的相关功能,所以在基础功能上较为简单,不支持Redis的原生命令操作,比如不支持字符串操作等

使用演示

pom依赖

1<dependency>2<groupId>org.redisson</groupId>3<artifactId>redisson</artifactId>4<version>3.12.5</version>5</dependency>

redisson连接单机单实例Redis

redisson连接哨兵模式Redis

1importorg.redisson.Redisson; 2importorg.redisson.api.RedissonClient; 3importorg.redisson.config.Config; 4 5/** 6*@author爱做梦的锤子 7*@create2020/7/17 8*/ 9publicclassSentinelRedisson{1011privateConfigconfig;1213/**14*连接哨兵模式redis15*16*@parammasterNameredis的master名称17*@paramsentinels哨兵的连接信息redis://sentinelHost:sentinelPort18*@parampasswordredis密码19*/20publicSentinelRedisson(StringmasterName,String[]sentinels,Stringpassword){21config=newConfig();22config.useSentinelServers()23.setMasterName(masterName)24.addSentinelAddress(sentinels)25.setPassword(password);2627}2829/**30*连接redis31*32*@return一个RedissonClient客户端33*/34publicRedissonClientconnect(){35RedissonClientredissonClient=Redisson.create(config);36returnredissonClient;37}3839}

redisson连接集群模式Redis

1importorg.redisson.Redisson; 2importorg.redisson.api.RedissonClient; 3importorg.redisson.config.Config; 4 5/** 6*@author爱做梦的锤子 7*@create2020/7/17 8*/ 9publicclassClusterRedisson{1011privateConfigconfig;1213/**14*连接cluster模式的redis15*16*@paramredisNodesredis集群中节点信息redis://nodeHost:nodePort17*@parampasswordredis密码18*/19publicClusterRedisson(String[]redisNodes,Stringpassword){20config=newConfig();21config.useClusterServers()22.addNodeAddress(redisNodes)23.setPassword(password);2425}2627/**28*连接redis29*30*@return一个RedissonClient客户端31*/32publicRedissonClientconnect(){33RedissonClientredissonClient=Redisson.create(config);34returnredissonClient;35}3637}

以上三段代码是使用Redisson连接三种模式下Redis的简易演示代码,下面再附上测试类代码

测试类

1/** 2*@author爱做梦的锤子 3*@create2020/7/20 4*/ 5publicclassRedissonTest{ 6 7privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(RedissonTest.class); 8privatestaticfinalStringTEST_KEY=”redisson”; 9privatestaticfinallongTEST_VALUE=100L;1011@Test12publicvoidsingleInstance(){13SingleInstanceRedissonsingleInstanceRedisson=newSingleInstanceRedisson(“192.168.56.90″,6379,”123456”);14RedissonClientredissonClient=singleInstanceRedisson.connect();15RAtomicLongatomicLong=redissonClient.getAtomicLong(TEST_KEY);16atomicLong.set(TEST_VALUE);17LOGGER.info(“redisson单机单实例:{}”,redissonClient.getAtomicLong(TEST_KEY).get());18Assert.assertEquals(TEST_VALUE,redissonClient.getAtomicLong(TEST_KEY).get());19}2021@Test22publicvoidsentinel(){23String[]sentinels=newString[]{“redis://192.168.56.91:26379″,”redis://192.168.56.92:26379″,”redis://192.168.56.93:26379”};24SentinelRedissonsentinelRedisson=newSentinelRedisson(“redis-master”,sentinels,”123456″);25RedissonClientredissonClient=sentinelRedisson.connect();26RAtomicLongatomicLong=redissonClient.getAtomicLong(TEST_KEY);27atomicLong.set(TEST_VALUE);28LOGGER.info(“redisson哨兵模式:{}”,redissonClient.getAtomicLong(TEST_KEY).get());29Assert.assertEquals(TEST_VALUE,redissonClient.getAtomicLong(TEST_KEY).get());30}3132@Test33publicvoidcluster(){34String[]redisNodes=newString[]{35″redis://192.168.56.81:6379″,36″redis://192.168.56.82:6379″,37″redis://192.168.56.83:6379″,38″redis://192.168.56.84:6379″,39″redis://192.168.56.85:6379″,40″redis://192.168.56.86:6379″41};42ClusterRedissonclusterRedisson=newClusterRedisson(redisNodes,”123456″);43RedissonClientredissonClient=clusterRedisson.connect();44RAtomicLongatomicLong=redissonClient.getAtomicLong(TEST_KEY);45atomicLong.set(TEST_VALUE);46LOGGER.info(“redisson集群模式:{}”,redissonClient.getAtomicLong(TEST_KEY).get());47Assert.assertEquals(TEST_VALUE,redissonClient.getAtomicLong(TEST_KEY).get());48}49}3.LettuceLettuce特点

Redis高级客户端,线程安全的,单个Lettuce连接可以在多个线程中操作

基于Netty实现,使用非阻塞IO,支持异步

对Redis基础操作支持全面,相对Jedis来说更加高效,不要考虑太多线程安全问题

相对Redisson来说分布式锁和分布式数据结构等都需要自行实现

Spring现有版本的默认redis客户端

使用演示

pom依赖

1<dependency>2<groupId>io.lettuce</groupId>3<artifactId>lettuce-core</artifactId>4<version>5.1.6.RELEASE</version>5</dependency>

lettuce连接单机单实例Redis

lettuce连接哨兵模式redis

1importio.lettuce.core.RedisClient; 2importio.lettuce.core.RedisURI; 3importio.lettuce.core.codec.Utf8StringCodec; 4importio.lettuce.core.masterslave.MasterSlave; 5importio.lettuce.core.masterslave.StatefulRedisMasterSlaveConnection; 6 7importjava.util.List; 8 9/**10*@author爱做梦的锤子11*@create2020/7/2012*/13publicclassSentinelLettuce{14privateList<RedisURI>redisURIList;1516/**17*连接哨兵模式的redis18*@paramredisURIList哨兵模式redis下的哨兵的信息,建议使用RedisURI.builder.sentinel填写哨兵信息来进行构造19*/20publicSentinelLettuce(List<RedisURI>redisURIList){21this.redisURIList=redisURIList;22}2324/**25*连接redis获取一个连接26*@return一个redis的连接27*/28publicStatefulRedisMasterSlaveConnection<String,String>connect(){29RedisClientredisClient=RedisClient.create();30StatefulRedisMasterSlaveConnection<String,String>connect=MasterSlave.connect(redisClient,newUtf8StringCodec(),redisURIList);31returnconnect;32}33}

lettuce连接集群模式Redis

1importio.lettuce.core.RedisURI; 2importio.lettuce.core.cluster.RedisClusterClient; 3importio.lettuce.core.cluster.api.StatefulRedisClusterConnection; 4 5importjava.util.List; 6 7/** 8*@author爱做梦的锤子 9*@create2020/7/2010*/11publicclassClusterLettuce{1213privateList<RedisURI>redisURIList;1415/**16*使用Lettuce连接集群模式redis17*@paramredisURIList集群中redis节点的信息,建议使用RedisURI.builder来进行构造18*/19publicClusterLettuce(List<RedisURI>redisURIList){20this.redisURIList=redisURIList;21}2223/**24*连接redis获取一个连接25*@return一个redis的连接26*/27publicStatefulRedisClusterConnection<String,String>connect(){28RedisClusterClientredisClusterClient=RedisClusterClient.create(redisURIList);29StatefulRedisClusterConnection<String,String>connect=redisClusterClient.connect();30returnconnect;31}323334}

以上三段代码是使用Lettuce连接三种模式下Redis的简易演示代码,下面再附上测试类代码

测试类

1/** 2*@author爱做梦的锤子 3*@create2020/7/20 4*/ 5publicclassLettuceTest{ 6 7privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(LettuceTest.class); 8privatestaticfinalStringTEST_KEY=”lettuce”; 9privatestaticfinalStringTEST_VALUE=”dream-hammer”;1011@Test12publicvoidSingleInstance(){13SingleInstanceLettucesingleInstanceLettuce=newSingleInstanceLettuce(“192.168.56.90″,6379,”123456”);14StatefulRedisConnection<String,String>connection=singleInstanceLettuce.connect();15RedisCommands<String,String>commands=connection.sync();16commands.set(TEST_KEY,TEST_VALUE);17LOGGER.info(“lettuce单机单实例:{}”,commands.get(TEST_KEY));18Assert.assertEquals(TEST_VALUE,commands.get(TEST_KEY));19}2021@Test22publicvoidsentinel(){23List<RedisURI>redisURIList=newArrayList<>();24redisURIList.add(RedisURI.builder().withSentinelMasterId(“redis-master”).withSentinel(“192.168.56.91”,26379).withPassword(“123456”).build());25redisURIList.add(RedisURI.builder().withSentinelMasterId(“redis-master”).withSentinel(“192.168.56.92”,26379).withPassword(“123456”).build());26redisURIList.add(RedisURI.builder().withSentinelMasterId(“redis-master”).withSentinel(“192.168.56.93”,26379).withPassword(“123456”).build());27SentinelLettucesentinelLettuce=newSentinelLettuce(redisURIList);28StatefulRedisMasterSlaveConnection<String,String>connection=sentinelLettuce.connect();29RedisCommands<String,String>commands=connection.sync();30commands.set(TEST_KEY,TEST_VALUE);31LOGGER.info(“lettuce哨兵模式:{}”,commands.get(TEST_KEY));32Assert.assertEquals(TEST_VALUE,commands.get(TEST_KEY));33}3435@Test36publicvoidcluster(){37List<RedisURI>redisURIList=newArrayList<>();38redisURIList.add(RedisURI.builder().withHost(“192.168.56.81”).withPort(6379).withPassword(“123456”).build());39redisURIList.add(RedisURI.builder().withHost(“192.168.56.82”).withPort(6379).withPassword(“123456”).build());40redisURIList.add(RedisURI.builder().withHost(“192.168.56.83”).withPort(6379).withPassword(“123456”).build());41redisURIList.add(RedisURI.builder().withHost(“192.168.56.84”).withPort(6379).withPassword(“123456”).build());42redisURIList.add(RedisURI.builder().withHost(“192.168.56.85”).withPort(6379).withPassword(“123456”).build());43redisURIList.add(RedisURI.builder().withHost(“192.168.56.86”).withPort(6379).withPassword(“123456”).build());44ClusterLettuceclusterLettuce=newClusterLettuce(redisURIList);45StatefulRedisClusterConnection<String,String>connection=clusterLettuce.connect();46RedisAdvancedClusterCommands<String,String>commands=connection.sync();47commands.set(TEST_KEY,TEST_VALUE);48LOGGER.info(“lettuce集群模式:{}”,commands.get(TEST_KEY));49Assert.assertEquals(TEST_VALUE,commands.get(TEST_KEY));50}5152}

二、在SpringBoot中使用Redis

在上一部分我们演示了直接使用不同的redis客户端连接Redis,并进行简单操作,在这一部分,我们将演示一下,在SpringBoot如何连接三种模式的redis

pom依赖

1<dependency>2<groupId>org.springframework.boot</groupId>3<artifactId>spring-boot-starter-data-redis</artifactId>4</dependency>

在application.yml文件中配置redis连接信息

1#连接单机单实例版的redis配置 2spring: 3redis: 4host:192.168.56.90 5port:6379 6password:123456 7database:0 8 9#连接哨兵模式的redis配置10spring:11redis:12sentinel:13master:redis-master14nodes:192.168.56.91:26379,192.168.56.92:26379,192.168.56.92:2637915password:1234561617#连接集群模式redis配置18spring:19redis:20cluster:21nodes:192.168.56.81:6379,192.168.56.82:6379,192.168.56.83:6379,192.168.56.84:6379,192.168.56.85:6379,192.168.56.86:637922password:123456

使用演示代码

1/** 2*@author爱做梦的锤子 3*@create2020/7/20 4*/ 5@Service(“redisSpring”) 6publicclassRedisSpring{ 7 8@Autowired 9privateRedisTemplateredisTemplate;1011@Autowired12privateStringRedisTemplatestringRedisTemplate;1314publicObjectredisTemplateOperate(Objectkey,Objectvalue){15redisTemplate.opsForValue().set(key,value);16returnredisTemplate.opsForValue().get(key);17}1819publicStringstringRedisTemplateOperate(Stringkey,Stringvalue){20stringRedisTemplate.opsForValue().set(key,value);21returnstringRedisTemplate.opsForValue().get(key);22}2324}

测试该功能的代码

1/** 2*@author爱做梦的锤子 3*@create2020/7/20 4*/ 5@SpringBootTest(classes=Application.class) 6@RunWith(SpringRunner.class) 7@EnableAutoConfiguration 8publicclassSpringTest{ 910privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(SpringTest.class);1112@Autowired13privateRedisSpringredisSpring;1415privatestaticfinalStringTEST_KEY=”spring”;16privatestaticfinalStringTEST_VALUE=”dream-hammer”;1718@Test19publicvoidtest(){20Objectvalue=redisSpring.redisTemplateOperate(TEST_KEY,TEST_VALUE);21LOGGER.info(“redisTemplate:{}”,value);22Assert.assertEquals(value,TEST_VALUE);23Strings=redisSpring.stringRedisTemplateOperate(TEST_KEY,TEST_VALUE);24LOGGER.info(“stringRedisTemplate:{}”,s);25Assert.assertEquals(TEST_VALUE,s);26}2728}总结

觉得不错就点个赞叭QAQ

发表评论

登录后才能评论