SpringBoot集成 Redis

SpringBoot整合Redis

一 添加redis的起步依赖



	org.springframework.boot
	spring-boot-starter-data-redis

二 配置redis的连接信息

#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379

三 注入RedisTemplate测试redis操作

	@RunWith(SpringRunner.class)
	@SpringBootTest(classes = SpringbootJpaApplication.class)
	public class RedisTest {
		@Autowired
		private UserRepository userRepository;
		
		@Autowired
		private RedisTemplate redisTemplate;
		
		@Test
		public void test() throws JsonProcessingException {

		//从redis缓存中获得指定的数据	
		String userListData = redisTemplate.boundValueOps("user.findAll").get();
		
		//如果redis中没有数据的话
		if(null==userListData){
			//查询数据库获得数据
			List all = userRepository.findAll();
			//转换成json格式字符串
			ObjectMapper om = new ObjectMapper();
			userListData = om.writeValueAsString(all);
			//将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
			redisTemplate.boundValueOps("user.findAll").set(userListData);
			System.out.println("===============从数据库获得数据===============");
		}else{
			System.out.println("===============从redis缓存中获得数据===============");
		}
			System.out.println(userListData);
		}
	}

你可能感兴趣的:((内),redis,SpringBoot,Redis)