Spring Boot 中使用Redis缓存泛型对象

定义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);
	}

}

 

转载于:https://my.oschina.net/yqz/blog/869205

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值