這裏只作單機版簡單集成,不過爲項目中使用redis
1.在pom文件中引入支持spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- springboot2.0的redis整合包多出lettuce鏈接池,須要commons-pool2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
2.直接在類中注入使用RedisTemplateapache
@RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate<String, User> redisTemplate; @Test public void test() throws Exception { stringRedisTemplate.opsForValue().set("bbb", "222"); System.out.println(stringRedisTemplate.opsForValue().get("bbb")); } @Test public void testObj() throws Exception { User user = new User(); user.setUserName("sean"); user.setPassWord("sean@123"); ValueOperations<String, User> operations = redisTemplate.opsForValue(); operations.set("com.jiafeng", user); operations.set("com.jiafeng.f", user, 1, TimeUnit.SECONDS); Thread.sleep(1000); boolean exists = redisTemplate.hasKey("com.jiafeng.f"); if (exists) { System.out.println("exists is true"); } else { System.out.println("exists is false"); } } }
在SpringBoot2.0以後,spring容器是自動的生成了StringRedisTemplate和RedisTemplate<Object,Object>,能夠直接注入。springboot