同一项目部署到多个tomcat,用一个 nginx 做了负截,具体服务请求到了哪个服务器不知道的情况下,不作处理最直接的问题是图片验证码和session会出现问题。
session问题可以通过配置nginx的ip_hash解决;
图片验证码问题是通过波总的指导了解到可以使用自定义CaptchaCache来集中缓存图片验证码。在此再次感谢波总!
下面上代码
public class MyCaptchaCache extends CaptchaCache {
@Override
public void put(Captcha captcha) {
//储存你的验证码 可以储存到数据库或者redis
//我的做法是储存在数据库内
Record record = new Record();
record.set("key", captcha.getKey());
record.set("value", captcha.getValue());
record.set("expireAt", captcha.getExpireAt());
Db.save("comm_captcha", record);
}
@Override
public Captcha get(String key) {
//从数据库内取出验证码
Record record = Db.findFirst("select * from comm_captcha where key=? order by id desc", key);
Captcha captcha = new Captcha(record.getStr("key"), record.getStr("value"));
return captcha;
}
@Override
public void remove(String key) {
//删除验证码
Record record = Db.findFirst("select * from comm_captcha where key=?", key);
Db.deleteById("comm_captcha", record.getInt("id"));
}
}最后在config内配置
me.setCaptchaCache(new MyCaptchaCache());
此外,建议几个改进:
1: 去掉所有 super 调用,例如: super.put(captcha); super.remove(key), 因为 super 的实在这种情况下应该完全抛弃
2:可以将继承 CaptchaCache 改成实现 ICaptchaCache 接口,这样也就没有 super 可以调用了
3: record.set("[Key]",...) 中的参数建议改成 "Key" , 不要加中括号
4:数据库字段名建议用符合 java 变量名规范的驼峰式