1. 添加相关依赖


<!--整合redis-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<!--springboot2.o默认使用的redis客户端是lettuce-->
			<exclusions>
				<exclusion>
					<groupId>io.lettuce</groupId>
					<artifactId>lettuce-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!--jedis-->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>

注:在SpringBoot1.0中使用的Redis客户端是Jedis,在SpringBoot2.0中使用的是lettuce

2. 配置redis


# Redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=admin
spring.redis.database=0
spring.redis.jedis.pool.max-active=100
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=3
  1. 基本用法
    使用SpringDataRedis提供的工具:StringRedisTemplate、RedisTemplate

	/**
	 * 使用stringRedisTemplate
	 * Redis数据类型:String、List、Set、ZSet、Hash
	 */
	@Test
	public void test1(){
//		 ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
//		 ListOperations<String, String> stringStringListOperations = stringRedisTemplate.opsForList();
//		 SetOperations<String, String> stringStringSetOperations = stringRedisTemplate.opsForSet();
//		 ZSetOperations<String, String> stringStringZSetOperations = stringRedisTemplate.opsForZSet();
//		 HashOperations<String, Object, Object> stringObjectObjectHashOperations = stringRedisTemplate.opsForHash();

		/*
		 * 操作String
		 */
//		 stringRedisTemplate.opsForValue().set("username","admin");
//		 System.out.println(stringRedisTemplate.opsForValue().get("username"));

		/*
		 * 操作List
		 */
//		 stringRedisTemplate.opsForList().leftPush("names","tom");
//		 stringRedisTemplate.opsForList().leftPushAll("names","aaa","bbb","ccc");
//		 System.out.println(stringRedisTemplate.opsForList().range("names",0,-1));

		/*
		 * 存储对象
		 */
//		Product product = new Product();
//		product.setId(1);
//		product.setName("曲奇");
//		product.setPrice(100);

		//将对象转换为json字符串
//		 String jsonString = JsonUtils.objectToJson(product);
//		 System.out.println(jsonString);
//		 stringRedisTemplate.opsForValue().set("user",jsonString);

		//将json字符串转换为对象
//		String str = stringRedisTemplate.opsForValue().get("user");
//		User u = JsonUtils.jsonToObject(str, User.class);
//		System.out.println(u);
	}

	/**
	 * 使用redisTemplate
	 */
	@Test
	public void test2(){
		redisTemplate.opsForValue().set("sex","male");
		Object sex = redisTemplate.opsForValue().get("sex");
		System.out.println(sex);
	}

	/**
	 * 使用工具类RedisUtils
	 */
	@Test
	public void test3(){
		redisUtils.set("age","21",20);
		System.out.println(redisUtils.get("age"));
	}
	@Test
	public void test4(){
		redisUtils.set("hello","world");
		System.out.println(redisUtils.get("hello"));
	}
}


下载地址:

SpringBoot 整合 redis 1.0

Github完整版: https://github.com/MacroFei/linkpro/tree/master/springboot-first-redis