定义cache配置类
@Configuration
@EnableCaching
public class SpringCacheConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
factory.setHostName("localhost");
factory.setPort(6379);
return factory;
}
@Bean
<T> RedisTemplate<String, T> redisTemplate() {
RedisTemplate<String, T> template = new RedisTemplate<String, T>();
template.setConnectionFactory(jedisConnectionFactory());
template.setStringSerializer(new StringRedisSerializer());
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
template.setEnableDefaultSerializer(true);
template.afterPropertiesSet();
return template;
}
}
定义主类
@SpringBootApplication
public class Main extends SpringBootServletInitializer {
//打war包时需重写SpringBootServletInitializer.configure
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Main.class);
}
public static void main(String[] args) throws Exception {
new SpringApplicationBuilder().sources(Main.class).properties("spring.config.name=application")
.bannerMode(Mode.OFF).run(args);
}
}
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
public class RedisTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, Person> redisTemplate;
@Test
public void set() throws Exception {
// 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
BoundHashOperations<String, String, Integer> ho = redisTemplate.boundHashOps("weather");
ho.put("北京", 1);
ho.put("上海", 2);
Assert.assertTrue(redisTemplate.boundHashOps("weather").size() == 2);
}
@Test
public void setObject() throws Exception {
BoundValueOperations<String, Person> op = redisTemplate.boundValueOps("person");
Person p = new Person();
p.setId(100);
p.setName("jack");
op.set(p);
op = redisTemplate.boundValueOps("person");
Assert.assertNotNull(op.get());
Assert.assertEquals(op.get().getId(), 100);
}
}