spring整合redis
使用版本
redis-4.0.6
jedis-2.9.0.jar
spring4.3.13
spring-data-redis-1.8.3.jar
spring-data-commons-2.0.1.jar
一共两篇,第一篇是java直接使用redis,第二篇使用spring整合redis。
先看一下目录:
service里面是本篇使用的三个文件,目录有两个spring的配置文件,user里面的文件在上一篇介绍过了(不在贴出来了)。
首先简单的实现一下spring+redis,UserService.java:
package service; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; import user.User; /** * @author 朱宏亮 * @version 创建时间:2017年12月19日 下午4:41:56 * 简单的spring整合redis 没有自动监听信息的 */ @Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void test(){ String paramK = "spring"; String paramV = "Hello,spring-redis-data!!!"; redisTemplate.opsForValue().set(paramK, paramV); } public void add(){ //添加一个 key ValueOperations<String, Object> value = redisTemplate.opsForValue(); value.set("zhl", "hello word"); } public void get(){ //获取 System.out.println("\n获取String:"); ValueOperations<String, Object> value = redisTemplate.opsForValue(); System.out.println(value.get("zhl")); System.out.println("删除zhl"); redisTemplate.delete("zhl"); System.out.println(value.get("zhl")); } public void addHash(){ //添加 一个 hash集合 HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); Map<String,Object> map = new HashMap<String,Object>(); map.put("name", "朱宏亮"); map.put("age", "26"); hash.putAll("userMap", map); } public void getHash(){ //获取 map System.out.println("\n获取HashMap:"); HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); System.out.println(hash.entries("userMap")); System.out.println("删除userMap"); redisTemplate.delete("userMap"); System.out.println(hash.entries("userMap")); } public void addList(){ //添加 一个 list 列表 ListOperations<String, Object> list = redisTemplate.opsForList(); list.rightPush("zhlList", "朱宏亮1"); list.rightPush("zhlList", "26"); } public void getList(){ //输出 list System.out.println("\n获取list:"); ListOperations<String, Object> list = redisTemplate.opsForList(); System.out.println(list.range("zhlList", 0, 100)); System.out.println("删除list"); redisTemplate.delete("zhlList"); System.out.println(list.range("zhlList", 0, 100)); } public void addSet(){ //添加 一个 set 集合 SetOperations<String, Object> set = redisTemplate.opsForSet(); set.add("zhlSet", "朱宏亮"); set.add("zhlSet", "26"); set.add("zhlSet", "178cm"); } public void getSet(){ //输出 set 集合 System.out.println("\n获取set集合:"); SetOperations<String, Object> set = redisTemplate.opsForSet(); System.out.println(set.members("zhlSet")); System.out.println("删除zhlSet"); redisTemplate.delete("zhlSet"); System.out.println(set.members("zhlSet")); } public void addSet2(){ //添加有序的 set 集合 ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.add("zhlSet2", "朱宏亮", 0); zset.add("zhlSet2", "26", 1); zset.add("zhlSet2", "178cm", 2); } public void getSet2(){ //输出有序 set 集合 System.out.println("\n获取有序set集合:"); ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); System.out.println(zset.rangeByScore("zhlSet2", 0, 20)); System.out.println("删除zhlSet2"); redisTemplate.delete("zhlSet2"); System.out.println(zset.rangeByScore("zhlSet2", 0, 20)); } public void addUser(){ User user = new User(); user.setId("99"); user.setName("zhl朱宏亮"); user.setPhone("18628888888"); user.setAddress("北京市海淀区西二旗"); ValueOperations<String, Object> value = redisTemplate.opsForValue(); value.set("user", user); } public void getUser(){ System.out.println("\n获取User对象:"); ValueOperations<String, Object> value = redisTemplate.opsForValue(); User user = (User) value.get("user"); System.out.println(user.getId()); System.out.println(user.getName()); System.out.println(user.getPhone()); System.out.println(user.getAddress()); System.out.println("删除user"); redisTemplate.delete("user"); System.out.println(value.get("user")); } @SuppressWarnings("resource") public static void main(String[] args){ ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); UserService userService = (UserService) factory.getBean("userService"); //userService.test(); userService.add(); userService.get(); userService.addHash(); userService.getHash(); userService.addList(); userService.getList(); userService.addSet(); userService.getSet(); userService.addSet2(); userService.getSet2(); userService.addUser(); userService.getUser(); } }
再来看看我们使用的配置文件applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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 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"> <context:component-scan base-package="service" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="32"></property> <property name="maxIdle" value="6"></property> <property name="testOnBorrow" value="true" /> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="jedisPoolConfig"></property> <property name="hostName" value="你的redis ip"></property> <property name="port" value="6379"></property> <property name="password" value="你的redis密码"></property> <property name="timeout" value="5500"></property> <property name="usePool" value="false"></property><!-- 连接池如果设置为true的话,程序永远不会结束,我这里仅测试学习使用,所以设置为false --> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"></property> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> </bean> </beans>
接下来直接运行UserService.java,能在控制台看到:
获取String: hello word 删除zhl null 获取HashMap: {name=朱宏亮, age=26} 删除userMap {} 获取list: [朱宏亮1, 26] 删除list [] 获取set集合: [26, 178cm, 朱宏亮] 删除zhlSet [] 获取有序set集合: [朱宏亮, 26, 178cm] 删除zhlSet2 [] 获取User对象: 99 zhl朱宏亮 18628888888 北京市海淀区西二旗 删除user null
接下来我们使用Spring整合redis,做一个发布/订阅模式
先看看订阅者自动监听的代码TopicMessageListener.java:
package service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.core.RedisTemplate; import user.User; /** * @author 朱宏亮 * @version 创建时间:2017年12月21日 下午5:51:01 * 类说明 spring整合redis 消息自动监听 */ public class TopicMessageListener implements MessageListener{ @Autowired private RedisTemplate<String, Object> redisTemplate; public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @Override public void onMessage(Message message, byte[] pattern) { System.out.println("=============================="); String cName = redisTemplate.getValueSerializer().deserialize(message.getBody()).getClass().getSimpleName(); System.out.println("类名:"+cName); if(cName.equals("String")){ System.out.println("接受到的数据:"+redisTemplate.getValueSerializer().deserialize(message.getBody())); System.out.println("topicName:"+new String(message.getChannel())); System.out.println("topicName:"+new String(pattern)); } if(cName.equals("User")){ User user = (User) redisTemplate.getValueSerializer().deserialize(message.getBody()); System.out.println("User.id:"+user.getId()); System.out.println("User.name:"+user.getName()); System.out.println("User.phone:"+user.getPhone()); System.out.println("User.address:"+user.getAddress()); System.out.println("topicName:"+new String(message.getChannel())); System.out.println("topicName:"+new String(pattern)); } } }
发布者TopicProducer.java:
package service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import user.User; /** * @author 朱宏亮 * 类说明 spring整合redis 消息发布者 */ @Component public class TopicProducer { @Autowired private RedisTemplate<String, Object> template; public void sendMessage(){ template.convertAndSend("redisChat", "我是中文"); User user = new User(); user.setId("88"); user.setName("朱宏亮"); user.setPhone("18628888888"); user.setAddress("中关村软件园"); template.convertAndSend("redisChat", user); template.convertAndSend("redisChat", "HELLO WORLD"); template.convertAndSend("redisChat", "辉煌国际"); template.convertAndSend("redisChat", "羊肉串"); template.convertAndSend("redisChat", "布劳威尔不动点"); User user2 = new User(); user2.setId("99"); user2.setName("打杂的"); user2.setPhone("17788889999"); user2.setAddress("朝阳区建外soho"); template.convertAndSend("redisChat", user2); } @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:ApplicationContext2.xml"); TopicProducer producer = (TopicProducer) factory.getBean("topicProducer"); producer.sendMessage(); } }
配置文件ApplicationContext2.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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 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"> <context:component-scan base-package="service" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="32"></property> <property name="maxIdle" value="6"></property> <property name="testOnBorrow" value="true" /> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="jedisPoolConfig"></property> <property name="hostName" value="8.8.8.8"></property> <property name="port" value="6379"></property> <property name="password" value=""></property> <property name="timeout" value="5500"></property> <property name="usePool" value="false"></property> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"></property> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> </bean> <bean id="topicMessageListener" class="service.TopicMessageListener"> <property name="redisTemplate" ref="redisTemplate"></property> </bean> <bean id="topicContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy"> <property name="connectionFactory" ref="jedisConnectionFactory"/> <property name="taskExecutor"> <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler"> <property name="poolSize" value="3"></property> </bean> </property> <property name="messageListeners"> <map> <entry key-ref="topicMessageListener"> <bean class="org.springframework.data.redis.listener.ChannelTopic"> <constructor-arg value="redisChat"/> </bean> </entry> </map> </property> </bean> </beans>
让我们运行一下TopicMessageListener.java文件,在eclipse上输出:
2017-12-24 18:55:45,516 [main] INFO [org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7e0b37bc: startup date [Sun Dec 24 18:55:45 CST 2017]; root of context hierarchy 2017-12-24 18:55:45,632 [main] INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [ApplicationContext2.xml] 2017-12-24 18:55:46,755 [main] INFO [org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler] - Initializing ExecutorService 'org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler#754ba872' 2017-12-24 18:55:47,016 [main] INFO [org.springframework.context.support.DefaultLifecycleProcessor] - Starting beans in phase 2147483647 ============================== 类名:String 接受到的数据:我是中文 topicName:redisChat topicName:redisChat ============================== 类名:User User.id:88 User.name:朱宏亮 User.phone:18628888888 User.address:中关村软件园 topicName:redisChat topicName:redisChat ============================== 类名:String 接受到的数据:HELLO WORLD topicName:redisChat topicName:redisChat ============================== 类名:String 接受到的数据:辉煌国际 topicName:redisChat topicName:redisChat ============================== 类名:String 接受到的数据:羊肉串 topicName:redisChat topicName:redisChat ============================== 类名:String 接受到的数据:布劳威尔不动点 topicName:redisChat topicName:redisChat ============================== 类名:User User.id:99 User.name:打杂的 User.phone:17788889999 User.address:朝阳区建外soho topicName:redisChat topicName:redisChat