redis learning 2

First of all, the reason why the default port of redis is 6379 is that these 4 numbers are the numbers corresponding to MERZ on the 9-key input method, and merz is an Italian female artist that redis authors hate. Embed the name of the person he hates into his own work, this person is also quite humorous

 

It is very convenient to use redis in java, it is really convenient

The next jedis package will create a new Jedis object and connect it. The methods are very simple, such as get, set, etc.

If jedis stores an object, it must first serialize the object into a byte array and then store it in redis. To read an object is to obtain a byte array and deserialize it into an object. (java serialization is the process of converting objects into byte sequences, and deserialization is the other way around)

First the object implements the serializable interface

The second is to have a serialization and deserialization tool. The code is as follows: (roughly written)

ublic class SerializeUtil {
	public static byte[] serialize(Object obj){
		ObjectOutputStream east = null;
		ByteArrayOutputStream bos = null;
		
		try {
			bos = new ByteArrayOutputStream();
			east = new ObjectOutputStream (forest);
			oos.writeObject (obj);
			byte[] bytes = bos.toByteArray();
			return bytes;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}finally{
			try {
				bos.close();
				oos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
		return null;
	}
	
	public static Object unserialize(byte[] bytes){
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		
		try {
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		return null;
	}
}

 

Then just call

Jedis jedis = new Jedis("localhost");
		Person person = new Person();
		person.setAge(20);
		person.setName("mao");
		
		byte[] bytes = SerializeUtil.serialize(person);
		jedis.set("person:1".getBytes(), bytes);
		
		byte[] newB = jedis.get("person:1".getBytes());
		
		Person newP = (Person)SerializeUtil.unserialize(newB);
		
		System.out.println(newP.getName()+newP.getAge());

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326797964&siteId=291194637