@PostConstruct注解应用redis连接

本文介绍了一个使用@PostConstruct和@PreDestroy注解管理JedisPool生命周期的例子。通过@Component注解将JedisPoolWrapper注册为Spring Bean,并在启动时初始化Jedis连接池,确保服务可用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@PostConstruct注解
     被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
@Component
public class JedisPoolWrapper {


	private JedisPool jedisPool = null;
	
	@Autowired
	private Parameters parameters;
        //redis的一些基础的配置信息,创建放在一个类中,可以统一管理
	
	@PostConstruct
	public void init() throws BikeException {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(parameters.getRedisMaxTotal());
			config.setMaxIdle(parameters.getRedisMaxIdle());
			config.setMaxWaitMillis(parameters.getRedisMaxWaitMillis());

			jedisPool = new JedisPool(config,parameters.getRedisHost(),parameters.getRedisPort(),2000,parameters.getRedisAuth());
		} catch (Exception e) {
			log.error("Fail to initialize jedis pool", e);
			throw new BikeException("Fail to initialize jedis pool");
                  //自定义异常,log输出到文件
		}
	}

        //这样启动的时候可以直接get到redispool
	public JedisPool getJedisPool() {
		return jedisPool;
	}
	
}



@PreDestroy
     被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值