springboot获取资源文件,redis实例

常常需要做一些junit测试用例,也用到redis,这里就简单做个笔记吧。


其中application的内容入下


在系统启动时加载配置文件:入下代码:

@Configuration
public class RedisConfig {

	
	
	@Value("${spring.redis.host}")  
    private String hostName;  
    @Value("${spring.redis.port}")  
    private int port;  
	 	@Bean  
	    @ConfigurationProperties(prefix="spring.redis")  
	    public JedisPoolConfig getRedisConfig(){  
	        JedisPoolConfig config = new JedisPoolConfig();
	        return config;  
	    }  
	      
	    @Bean  
	    @ConfigurationProperties(prefix="spring.redis")  
	    public JedisConnectionFactory getConnectionFactory(){  
	        JedisConnectionFactory factory = new JedisConnectionFactory();  
	        JedisPoolConfig config = getRedisConfig();  
	        factory.setPoolConfig(config);
	        factory.setHostName(hostName);
	        factory.setPort(port);
	        return factory;  
	    }  
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(getConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }


}

直接使用实例:

@Component
public class RedisDao {
@Autowired
    public RedisTemplate<String, Object> redisTemplate;

    /**
     * 缓存value操作
     */
    public boolean cacheValue(String k, String v, long time) {
        String key = k;
        try {
            ValueOperations<String, Object> valueOps =  redisTemplate.opsForValue();
            valueOps.set(key, v);
            if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
            return true;
        } catch (Throwable t) {
            logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/goodlook0123/article/details/79724218