我们使用redis解决过期优惠券和红包等问题,并且在java环境中使用redis的消息通知。目前世面比较流行的java代码操作redis的AIP有:Jedis和RedisTemplate
Jedis是Redis官方推出的一款面向Java的客户端,提供了很多接口供Java语言调用。
SpringData Redis是Spring官方推出,可以算是Spring框架集成Redis操作的一个子框架,封装了Redis的很多命令,可以很方便的使用Spring操作Redis数据库。由于现代企业开发中都使用Spring整合项目,所以在API的选择上我们使用Spring提供的SpringData Redis
key操作
String操作
Hash操作
List操作
Set操作
Zset操作
特性:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NNd7pAmV-1649066464116)(https://github.com/Ricardo0324/SpringData-Redis/raw/main/images/image006-16490655695882.png)]
pom.xml文件中加载依赖
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>Redis-SpringData-Demo1artifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<spring.version>4.2.4.RELEASEspring.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<springdataredis.version>1.7.4.RELEASEspringdataredis.version>
<mysql.version>5.1.6mysql.version>
properties>
<dependencies>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.6.2version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-pool2artifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-redisartifactId>
<version>${springdataredis.version}version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.8version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.10version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.9version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
dependencies>
<build>
<finalName>Redis-SpringData-Demo1finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.2version>
<configuration>
<source>1.7source>
<target>1.7target>
<encoding>UTF-8encoding>
<showWarnings>trueshowWarnings>
configuration>
plugin>
plugins>
pluginManagement>
build>
project>
整合springData redis的配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
<description>spring-data整合jedisdescription>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory">property>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer">bean>
property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer">bean>
property>
bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="127.0.0.1">property>
<property name="port" value="6379">property>
<property name="database" value="0">property>
<property name="poolConfig" ref="poolConfig">property>
bean>
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="5">property>
<property name="maxTotal" value="10">property>
<property name="testOnBorrow" value="true">property>
bean>
beans>
然后测试环境是否搭建成功
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.logging.Logger;
/**
* @ClassName RedisTest
* @Description: //TODO 测试redis
* @Author wyq
* @Date 2022/3/30 16:50
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class RedisTest {
private static Logger log = Logger.getLogger(String.valueOf(RedisTest.class));
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void testSend() {
redisTemplate.opsForValue().set("itwyq01", "Hello Redis");
String value = redisTemplate.opsForValue().get("itwyq01");
log.info("从redis中获取的数据:" + value);
}
}
cmd进入Redis安装目录,执行命令启动Redis服务
D:\Redis>redis-server.exe redis.windows.conf
运行程序,效果如下。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OT02NMcr-1649066464117)(https://github.com/Ricardo0324/SpringData-Redis/raw/main/images/image-20220404172222109.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5NEuN1Xr-1649066464118)(https://github.com/Ricardo0324/SpringData-Redis/raw/main/images/image-20220404172601162.png)]
至此已经搭建完成了SpringData Redis的操作环境,并且操作成功
如果要在java代码中监听redis的主题消息,我们还需要自定义处理消息的监听器,代码如下
package com.wyq.listener;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
/**
* @ClassName RedisMessageListener
* @Description: //TODO redis信息的监听器
* @Author wyq
* @Date 2022/3/30 17:03
*/
public class RedisMessageListener implements MessageListener {
/**
* 处理redis消息:当从redis中获取消息后,打印主题名称和基本的消息
*/
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("从channel为" + new String(message.getChannel())
+ "中获取了一条新的消息,消息内容:" + new String(message.getBody()));
}
}
这样我们就定义好了一个消息监听器,当订阅的频道有一条新的消息发送过来之后,通过此监听器中的onMessage方法处理
当监听器程序写好之后,我们还需要在springData redis的配置文件中添加监听器以及订阅的频道主题,
我们测试订阅的频道为ITWYQ,添加配置如下:
<bean class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter" id="messageListener">
<constructor-arg>
<bean class="com.wyq.listener.RedisMessageListener"/>
constructor-arg>
bean>
<bean class="org.springframework.data.redis.listener.RedisMessageListenerContainer" id="redisContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="messageListeners">
<map>
<entry key-ref="messageListener">
<list>
<bean class="org.springframework.data.redis.listener.ChannelTopic">
<constructor-arg value="ITWYQ">constructor-arg>
bean>
list>
entry>
map>
property>
bean>
配置好消息监听,已经订阅的主题之后就可以启动程序进行测试了。由于有监听程序在,只需要已java代码的形式启动,创建spring容器(当spring容器加载之后,会创建监听器一直监听对应的消息)。
package com.wyq.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @ClassName RedisTest02
* @Description: //TODO 测试监听器
* @Author wyq
* @Date 2022/3/30 17:10
*/
public class RedisTest02 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-redis.xml");
}
}
当程序启动之后,会一直保持运行状态。即订阅了ITWYQ频道的消息,这个时候通过redis的客户端程序(redis-cli)发布一条消息
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PA45eats-1649066464119)(https://github.com/Ricardo0324/SpringData-Redis/raw/main/images/image-20220404173747561.png)]
命令解释:
publish topic名称 消息内容 : 向指定频道发送一条消息
发送消息之后,我们在来看java控制台输出验证是否获取到了此消息
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WAyZZTSh-1649066464120)(https://github.com/Ricardo0324/SpringData-Redis/raw/main/images/image-20220404173835487.png)]
至此我们已经完成了在java代码中获取redis的消息通知
参考视频:https://www.bilibili.com/video/BV1a4411a7b3?spm_id_from=333.337.search-card.all.click