朱宏亮
  • 首页
  • 说明

Tag spring-data-redis-1.8.3.jar

个人站点

  • 首页   /  
  • 标签: "spring-data-redis-1.8.3.jar"
java, Redis, Spring 12月 24,2017

spring整合redis学习(2)

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

这个时候消息订阅者会一直保持监听状态,就是这么简单
程序源码下载地址:https://gitee.com/zhuhongliang/RedisStudy

作者 朱宏亮
java, Redis, Spring 12月 24,2017

spring整合Redis学习(1)

java直接使用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。

先看下目录(就五个文件):

user目录下的User.java是将要使用redis存储的类,SerializeUtil.java是用来序列化和反序列化类文件的。

先看一下User.java:

package user;

import java.io.Serializable;

/** 
* @author 朱宏亮
* @version 创建时间:2017年12月19日 下午2:00:53 
* 类说明 
*/
public class User implements Serializable{

   
    private static final long serialVersionUID = 1L;
  
    private String id;
    private String name;
    private String phone;
    private String address;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
}

SerializeUtil.java:

package user;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/** 
* @author 朱宏亮
* @version 创建时间:2017年12月19日 下午2:23:20 
* 类说明 
*/
public class SerializeUtil {

    /**
     * 序列化
     * @param object
     * @return
     */
    public static byte[] serialize(Object object){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try{
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        }catch(Exception e){
            
        }
        return null;
    }
    
    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes){
        ByteArrayInputStream bais = null;
        try{
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        }catch(Exception e){
            
        }
        return null;
    }
    

}

然后我们写一个简单的java代码来连接redis,看看能否成功

Test.java:

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import redis.clients.jedis.Jedis;
import user.SerializeUtil;
import user.User;
/**
 * 和spring没有关系
 * @author Administrator
 *
 */
public class Test {

    @SuppressWarnings("resource")
    public static void main(String[] args) {

        //连接 Redis 服务
        Jedis jedis = new Jedis("你的Redis服务的ip地址", 6379);
        jedis.auth("redis的密码,没有密码的就把这行注释了");
        
        //查看服务是否运行
        System.out.println("Server is running: "+jedis.ping()); 
        
        jedis.set("test", "123");
        System.out.println("test:"+jedis.get("test"));
        System.out.println("=============================================");
        
        
        jedis.lpush("skill-list", "如来神掌" );
        jedis.lpush("skill-list", "独孤九剑");
        jedis.lpush("skill-list", "凌波微步");
        
        List list = jedis.lrange("skill-list", 0, 2);
        
        for(String s : list){
            System.out.println(s);
        }
        System.out.println("=============================================");
        
        
        Set keys = jedis.keys("*");
        Iterator it = keys.iterator();
        while(it.hasNext()){
            String key = it.next();
            System.out.println(key);
        }
        System.out.println("=============================================");
        
        /**
         * 存一个对象
         */
        User user1 = new User();
        user1.setId("18");
        user1.setName("蜡笔小新");
        user1.setPhone("18628889999");
        user1.setAddress("北京市海淀区中关村软件园大飞碟");
        
        jedis.set("user1".getBytes(), SerializeUtil.serialize(user1));
    
        User user2 = (User) SerializeUtil.unserialize(jedis.get("user1".getBytes()));
        System.out.println("id:\t"+user2.getId());
        System.out.println("name:\t"+user2.getName());
        System.out.println("phone:\t"+user2.getPhone());
        System.out.println("address:\t"+user2.getAddress());
        
  
              
    }

}

运行Test.java文件,在Eclipse的控制台看到输出:

Server is running: PONG
test:123
=============================================
凌波微步
独孤九剑
如来神掌
=============================================
user1
spring-redis-key
redisChat
test
skill-list
redisUser
=============================================
id:	18
name:	蜡笔小新
phone:	18628889999
address:	北京市海淀区中关村软件园大飞碟

上面运行的没毛病,然后我们实现一个简单的发布者和订阅者自动监听,俩文件。

发布者TestProducer.java:

import redis.clients.jedis.Jedis;

/** 
* @author 朱宏亮
* @version 创建时间:2017年12月21日 下午4:48:28 
* 类说明  消息发布者   和spring没有关系
*/
public class TestProducer{
	
	public static String ip = "你的redisip";
	
	public static String pw = "你的密码";
    @SuppressWarnings("resource")
	public static void main(String[] args) throws InterruptedException {
        
    	
     /*
        for(int i = 0 ; i < 3 ; i ++ ){
            Thread thread = new Thread(){
                public void run() {
                    go();
                }
            };
            thread.start();
       
        }*/
        
        
        Jedis jedis = new Jedis( ip , 6379); 
        jedis.auth(pw);
        jedis.publish("redisChat", "Redis真好玩");  
        Thread.sleep(2000);  
        jedis.publish("redisChat", "请开始你的表演");  
        Thread.sleep(2000);  
        jedis.publish("redisChat", "皮皮虾我们走!");  
   
        
    }

    @SuppressWarnings("resource")
	public static void go(){
       
        Jedis jedis = new Jedis( ip , 6379);  
        jedis.auth(pw);
        jedis.publish("redisChat", "又一个发布者");  
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }  
        jedis.publish("redisChat", "发送一些信息");  
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }  
        jedis.publish("redisChat", "嘿嘿嘿");  
    }
}

自动监听的订阅者TestConsumer.java:

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/** 
* @author 朱宏亮
* @version 创建时间:2017年12月21日 下午4:35:51 
* 类说明 消息订阅者,消息监听  和spring没有关系
*/
public class TestConsumer extends JedisPubSub {

   

    @Override
    public void onMessage(String channel, String message) {
        System.out.println(channel + "," + message);
    }

    @Override
    public void onPMessage(String pattern, String channel, String message) {
        System.out.println(pattern + "," + channel + "," + message);

    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("onSubscribe: channel[" + channel + "]," + "subscribedChannels[" + subscribedChannels + "]");
    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println("onUnsubscribe: channel[" + channel + "], " + "subscribedChannels[" + subscribedChannels + "]");
    }

    @Override
    public void onPUnsubscribe(String pattern, int subscribedChannels) {
        System.out.println("onPUnsubscribe: pattern[" + pattern + "]," + "subscribedChannels[" + subscribedChannels + "]");

    }

    @Override
    public void onPSubscribe(String pattern, int subscribedChannels) {
        System.out.println("onPSubscribe: pattern[" + pattern + "], " + "subscribedChannels[" + subscribedChannels + "]");

    }

    
    

    
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        Jedis jedis = new Jedis("你的redisip", 6379);  
        jedis.auth("你的redis密码");
        TestConsumer listener = new TestConsumer();  
        jedis.subscribe(listener, "redisChat");  
    }
    
    
    

}

然后我们先启动TestConsumer.java,然后再启动TestProducer.java,Eclipse的控制台输出:

onSubscribe: channel[redisChat],subscribedChannels[1]
redisChat,Redis真好玩
redisChat,请开始你的表演
redisChat,皮皮虾我们走!

看到这个输出之后,发现TestConsumer.java文件并没结束,他还保持着监听状态,当发布者再次发布消息时,订阅者还是可以接受到信息。

使用java使用redis就是这么简单,下一篇来看看spring+整合redis的操作。

源代码下载地址: https://gitee.com/zhuhongliang/RedisStudy

 

作者 朱宏亮

分类目录

  • ActiveMQ
  • apache
  • docker
  • dubbo
  • Eclipse
  • elasticsearch
  • git
  • IntelliJ
  • jar
  • java
  • jsp
  • kafka
  • linux
  • MongoDB
  • MyBatis
  • MySql
  • nginx
  • php
  • Redis
  • Spring
  • SpringMVC
  • Tomcat
  • 个人日志
  • 未分类
  • 缓存
  • 阿里云相关

标签

ActiveMQ annotation apache Eclipse elasticsearch elasticsearch-rest-high-level-client feign git ik中文分词 IntelliJ java java使用redis jdbc jedis-2.9.0.jar jsp kafka kafka_2.11-1.0.0 linux maven Mybatis mysql mysql5.7 nginx php Redis redis-4.0.6 Spring spring-data-commons-2.0.1.jar spring-data-redis-1.8.3.jar spring-kafka spring4.3.13 springboot springcloud Springmvc spring整合redis tomcat zookeeper 反向代理 启动报错 安装 控制反转 数据注入 注解 缓存 项目路径

近期评论

    功能

    • 登录
    • 文章RSS
    • 评论RSS
    • WordPress.org

    我的联系邮箱:zhuhongliang.king@qq.com.