SpringData 整合Redis

1 创建项目,导入jar包

jar包
SpringData 整合Redis_第1张图片

2 编写配置文件

redis.properties

redis.pool.maxTotal=20
redis.pool.maxIdle=10
redis.pool.minIdle=5
redis.conn.hostName=127.0.0.1
redis.conn.port=6379

applicationContext.xml




	
	 
	
	
		
		
		
	
	
	
		
		
		
	
	
	
		
		
		
		
		
		
			
		
		
			
		
	

3 测试

在运行之前先开启redis-server,创建一个Users对象

package per.czt.test;

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.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import per.czt.pojo.Users;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
	@Autowired
	private RedisTemplate redisTemplate;
	/*
	 * 添加键值对
	 */
	/*@Test
	public void test() {
		redisTemplate.opsForValue().set("key", "test");;
		
	}*/
	/*
	 * 获取redis中的数据
	 */

	@Test
	public void test1() {
		String value=(String) redisTemplate.opsForValue().get("key");
		System.out.println(value);
	}
	/*
	 * 添加users
	 */
	
	/*@Test
	  public void test2() {
		Users users=new Users();
		users.setUserid(2);
        users.setUserage(13);
        users.setUsername("张三");
        //对值做jdk序列化处理
        this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        this.redisTemplate.opsForValue().set("user", users);
	}*/
	/*
	 * 获取Users
	 */
	@Test
	public void test3() {
	     //对值做jdk序列化处理
		this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		Users users=(Users) this.redisTemplate.opsForValue().get("user");
		System.out.println(users);
	}
	/*
	 * 添加Users json格式
	 */
	/*@Test
	public void test4() {
		Users users=new Users();
		users.setUserid(9);
        users.setUserage(18);
        users.setUsername("李四");
         //对值做jackson序列化处理,转换为json格式
        this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));
        
        this.redisTemplate.opsForValue().set("usersjson",users);
        
	}*/
	/*
	 * 获取Users json格式
	 */
	@Test
	public void test5() {
	    //对值做jackson序列化处理,转换为json格式
		this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));
		Users users=(Users) this.redisTemplate.opsForValue().get("usersjson");
		System.out.println(users);
	}
}

你可能感兴趣的:(Spring,Data,Redis)