问题描述:
线上集群环境,前端可能从A服务器取得验证码,而验证是到B服务器
默认的hashmap store是保存在单个Jvm内存中的,这样验证就会有问题
解决办法:
重写CaptchaStore,把信息存在缓存中(memcached或redis)
1.重写 MyCaptchaStore 实现 CaptchaStore
public class MyCaptchaStore implements CaptchaStore {
@Autowired
private MemcachedService memcachedService;
@Override
public boolean hasCaptcha(String id) {
CaptchaAndLocale captcha = (CaptchaAndLocale) memcachedService.get(id);
return captcha == null ? false : true;
}
@Override
public void storeCaptcha(String id, Captcha captcha) throws CaptchaServiceException {
try {
memcachedService.add(id,new CaptchaAndLocale(captcha));
} catch (Exception e) {
throw new CaptchaServiceException(e);
}
}
@Override
public void storeCaptcha(String id, Captcha captcha, Locale locale) throws CaptchaServiceException {
try {
memcachedService.add(id,new CaptchaAndLocale(captcha,locale));
} catch (Exception e) {
throw new CaptchaServiceException(e);
}
}
@Override
public boolean removeCaptcha(String id) {
memcachedService.remove(id);
return true;
}
@Override
public Captcha getCaptcha(String id) throws CaptchaServiceException {
CaptchaAndLocale captchaAndLocale = (CaptchaAndLocale) memcachedService.get(id);
return captchaAndLocale != null ? (captchaAndLocale.getCaptcha()) : null;
}
@Override
public Locale getLocale(String id) throws CaptchaServiceException {
CaptchaAndLocale captchaAndLocale = (CaptchaAndLocale) memcachedService.get(id);
return captchaAndLocale != null ? (captchaAndLocale.getLocale()) : null;
}
@Override
public int getSize() {
return 0;
}
@Override
public Collection getKeys() {
return null;
}
@Override
public void empty() {
}
@Override
public void initAndStart() {
}
@Override
public void cleanAndShutdown() {
}
}
2.配置spring.xml,添加
<!-- 验证码配置 -->
<bean id="captchaService"
class="com.octo.captcha.service.multitype.GenericManageableCaptchaService">
<constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">
<ref bean="myCaptchaStore"/>
</constructor-arg>
<constructor-arg index="1" ref="imageEngine" />
<constructor-arg type="int" index="2" value="180" />
<constructor-arg type="int" index="3" value="100000" />
<constructor-arg type="int" index="4" value="75000" />
</bean>
<bean id="myCaptchaStore" class="com.xxxx.internal.MyCaptchaStore"/>
参考文章:http://zhanshenny.iteye.com/blog/2098779