标签:max key add bean core open fan repo system
背景:基于实践1中,我们使用Redis做为缓存。
(转载请注明来源:cnblogs coder-fang)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.max-active=8
package com.test.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory); return stringRedisTemplate; } }
package com.test.demo.db.repo.nosql; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; @Repository public class RedisRepository { @Autowired RedisTemplate<String, String> redisTemplate; public void add(String key,String value) { redisTemplate.opsForValue().set(key, value); } public void add(String key,String value,Long time) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.MINUTES); } public String get(String key) { return redisTemplate.opsForValue().get(key); } public void delete(String key) { redisTemplate.opsForValue().getOperations().delete(key); } }
package com.test.demo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.test.demo.db.repo.nosql.RedisRepository; @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired RedisRepository redisRepo; @Test public void testRedis(){ redisRepo.add("test", "123", 1L); String val = redisRepo.get("test"); assertEquals(val, "123"); System.out.println(val); val = redisRepo.get("321"); System.out.println(val); assertNull(val); } }
YES,项目中使用redis已完成。
标签:max key add bean core open fan repo system
原文地址:http://www.cnblogs.com/coder-fang/p/7791502.html