SpringBoot集成 Redis

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xinyuezitang/article/details/97004221

SpringBoot整合Redis

一 添加redis的起步依赖

<!-- 配置使用redis启动器 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency

二 配置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<String, String> redisTemplate;
		
		@Test
		public void test() throws JsonProcessingException {

		//从redis缓存中获得指定的数据	
		String userListData = redisTemplate.boundValueOps("user.findAll").get();
		
		//如果redis中没有数据的话
		if(null==userListData){
			//查询数据库获得数据
			List<User> 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);
		}
	}

猜你喜欢

转载自blog.csdn.net/xinyuezitang/article/details/97004221