Authored by Gino Zhang

支持设置品牌动态加分

package com.yoho.search.dal;
import com.yoho.search.dal.model.ScoreRule;
/**
* Created by ginozhang on 2017/4/12.
*/
public interface ScoreRuleMapper {
ScoreRule selectByPrimaryKey(Integer id);
ScoreRule selectByRuleType(String ruleType);
int insert(ScoreRule record);
int updateByPrimaryKey(ScoreRule record);
int deleteByPrimaryKey(Integer id);
}
... ...
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.yoho.search.dal.ScoreRuleMapper" >
<resultMap id="BaseResultMap" type="com.yoho.search.dal.model.ScoreRule" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="rule_type" property="ruleType" jdbcType="VARCHAR" />
<result column="rule_values" property="ruleValues" jdbcType="VARCHAR" />
<result column="update_time" property="updateTime" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, rule_type, rule_values, update_time
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from score_rule
where id = #{id,jdbcType=INTEGER}
</select>
<select id="selectByRuleType" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from score_rule
where rule_type = #{ruleType,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from score_rule
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.yoho.search.dal.model.ScoreRule" >
insert into score_rule (id, rule_type, rule_values, update_time)
values (#{id,jdbcType=INTEGER}, #{ruleType,jdbcType=VARCHAR}, #{ruleValues,jdbcType=VARCHAR}, #{updateTime,jdbcType=INTEGER})
</insert>
<update id="updateByPrimaryKey" parameterType="com.yoho.search.dal.model.SuggestWordCustom" >
update score_rule
set rule_type = #{ruleType,jdbcType=VARCHAR},
rule_values = #{ruleValues,jdbcType=VARCHAR},
update_time = #{updateTime,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
... ...
package com.yoho.search.consumer.index.increment;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.yoho.error.event.SearchEvent;
import com.yoho.search.base.utils.ConvertUtils;
import com.yoho.search.base.utils.EventReportEnum;
import com.yoho.search.base.utils.ISearchConstants;
import com.yoho.search.consumer.service.base.ScoreRuleService;
import com.yoho.search.consumer.service.logic.ScoreRuleLogicService;
import com.yoho.search.core.es.utils.IgnoreSomeException;
import com.yoho.search.dal.model.ScoreRule;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* Created by gemingdan on 2017/3/15.
*/
@Component
public class ScoreRuleMqListener extends AbstractMqListener implements ChannelAwareMessageListener {
private static final Logger logger = LoggerFactory.getLogger(ScoreRuleMqListener.class);
@Autowired
private ScoreRuleService scoreRuleService;
@Autowired
private ScoreRuleLogicService scoreRuleLogicService;
@Override
public void onMessage(Message message, Channel channel) throws Exception {
try {
String messageStr = new String(message.getBody(), "UTF-8");
logger.info("[model=ScoreRuleMqListener] [message={}]", messageStr);
JSONObject json = JSONObject.parseObject(messageStr);
String action = json.getString("action");
if (ISearchConstants.ACTION_DELETE.equals(action)) {
deleteData(json.getString("data"));
} else {
updateData(json.getObject("data", Map.class));
}
} catch (Exception e) {
publisher.publishEvent(new SearchEvent(EventReportEnum.SUGGESTWORDCUSTOMMQLISTENER_ONMESSAGE.getEventName(), EventReportEnum.SUGGESTWORDCUSTOMMQLISTENER_ONMESSAGE.getFunctionName(),
EventReportEnum.SUGGESTWORDCUSTOMMQLISTENER_ONMESSAGE.getMoudleName(), "exception", IgnoreSomeException.filterSomeException(e), null));
Thread.sleep(1000);
throw e;
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
public void updateData(final Map data) throws Exception {
long begin = System.currentTimeMillis();
ScoreRule scoreRule = new ScoreRule();
scoreRule = (ScoreRule) ConvertUtils.toJavaBean(scoreRule, data);
if (scoreRule == null || scoreRule.getId() == null) {
return;
}
// 先推送到ZK
scoreRuleLogicService.tryUpdateFunctionScoreRule(scoreRule);
// 更新数据库
scoreRuleService.saveOrUpdate(scoreRule);
logger.info("[func=updateData][step=success][tableName={}][id={}][cost={}ms]", "score_rule", scoreRule.getId(), (System.currentTimeMillis() - begin));
}
public void deleteData(final String id) throws Exception {
if (StringUtils.isBlank(id)) {
return;
}
long begin = System.currentTimeMillis();
ScoreRule sourceData = scoreRuleService.selectByPrimaryKey(Integer.valueOf(id));
if (sourceData != null) {
// 先推送到ZK
scoreRuleLogicService.tryRemoveFunctionScoreRule(sourceData.getRuleType());
// 删除数据
scoreRuleService.delete(Integer.valueOf(id));
logger.info("[func=deleteData][step=success][tableName={}][id={}][cost={}ms]", "score_rule", id, System.currentTimeMillis() - begin);
}
}
}
... ...
package com.yoho.search.consumer.service.base;
import com.yoho.search.dal.ScoreRuleMapper;
import com.yoho.search.dal.model.ScoreRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ScoreRuleService {
@Autowired
protected ScoreRuleMapper scoreRuleMapper;
public ScoreRule selectByPrimaryKey(Integer id) {
if (id == null) {
return null;
}
return scoreRuleMapper.selectByPrimaryKey(id);
}
public void saveOrUpdate(ScoreRule scoreRule) {
if (scoreRule == null || scoreRule.getId() == null) {
return;
}
ScoreRule db = scoreRuleMapper.selectByPrimaryKey(scoreRule.getId());
if (db == null) {
//新增
scoreRuleMapper.insert(scoreRule);
} else {
//修改
scoreRuleMapper.updateByPrimaryKey(scoreRule);
}
}
public void delete(Integer id) {
scoreRuleMapper.deleteByPrimaryKey(id);
}
}
... ...
package com.yoho.search.consumer.service.logic;
import com.yoho.core.config.ConfigReader;
import com.yoho.search.dal.ScoreRuleMapper;
import com.yoho.search.dal.model.ScoreRule;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
/**
* Created by ginozhang on 2017/4/12.
*/
@Component
public class ScoreRuleLogicService implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(ScoreRuleLogicService.class);
private static final List<String> SUPPORT_RULE_TYPES = Arrays.asList("BRAND_INCREASE_RULE");
private static final String CONFIG_ROOT_PATH = "/yh/config";
private static final String FUNCTION_SCORE_RULE_KEY_TEMPLATE = "search.function.score.%s";
private static final String DEFAULT_RULE_VALUES = "-1";
@Autowired
private ScoreRuleMapper scoreRuleMapper;
@Autowired
private ConfigReader configReader;
@Resource(name = "curatorFramework")
private CuratorFramework client;
@Override
public void afterPropertiesSet() throws Exception {
for (String ruleType : SUPPORT_RULE_TYPES) {
ScoreRule scoreRule = scoreRuleMapper.selectByRuleType(ruleType);
if (scoreRule != null) {
tryUpdateFunctionScoreRule(scoreRule);
} else {
tryRemoveFunctionScoreRule(ruleType);
}
}
}
public void tryUpdateFunctionScoreRule(ScoreRule scoreRule) {
String key = String.format(FUNCTION_SCORE_RULE_KEY_TEMPLATE, scoreRule.getRuleType().toLowerCase());
String srcValue = configReader.getString(key, DEFAULT_RULE_VALUES);
if (!scoreRule.getRuleValues().equals(srcValue)) {
logger.info("[func=ScoreRuleLogicService.tryUpdateFunctionScoreRule][ruleType={}][srcValue={}][newValue={}]", scoreRule.getRuleType(), srcValue, scoreRule.getRuleValues());
publishToZk(scoreRule.getRuleType().toLowerCase(), scoreRule.getRuleValues());
}
}
public void tryRemoveFunctionScoreRule(String ruleType) {
String key = String.format(FUNCTION_SCORE_RULE_KEY_TEMPLATE, ruleType.toLowerCase());
String srcValue = configReader.getString(key, DEFAULT_RULE_VALUES);
if (!DEFAULT_RULE_VALUES.equals(srcValue)) {
logger.info("[func=ScoreRuleLogicService.tryRemoveFunctionScoreRule][ruleType={}][srcValue={}]", ruleType, srcValue);
publishToZk(ruleType.toLowerCase(), DEFAULT_RULE_VALUES);
}
}
private synchronized void publishToZk(String key, String value) {
try {
if (client.checkExists().forPath(CONFIG_ROOT_PATH) == null) {
client.create().creatingParentContainersIfNeeded().forPath(CONFIG_ROOT_PATH);
}
String path = CONFIG_ROOT_PATH + "/" + key;
if (this.client.checkExists().forPath(path) == null) {
this.client.create().forPath(path, value.getBytes("UTF-8"));
} else {
this.client.setData().forPath(path, value.getBytes("UTF-8"));
}
} catch (Exception e) {
logger.error("publish function score rule " + key + " to zk failed!", e);
}
}
}
... ...
... ... @@ -78,6 +78,7 @@
<rabbit:queue durable="true" exclusive="false" name="data_update_channel_productattribute" />
<rabbit:queue durable="true" exclusive="false" name="data_update_channel_suggestconversioncustom" />
<rabbit:queue durable="true" exclusive="false" name="data_update_channel_suggestwordcustom" />
<rabbit:queue durable="true" exclusive="false" name="data_update_channel_scorerule" />
<rabbit:template exchange="${search.mq.exchange}" id="amqpTemplate"
connection-factory="connectionFactory" message-converter="jsonMessageConverter" />
... ... @@ -158,6 +159,6 @@
<rabbit:listener queue-names="data_update_channel_productattribute" ref="productAttributeMqListener" />
<rabbit:listener queue-names="data_update_channel_suggestconversioncustom" ref="suggestConversionCustomMqListener" />
<rabbit:listener queue-names="data_update_channel_suggestwordcustom" ref="suggestWordCustomMqListener" />
<rabbit:listener queue-names="data_update_channel_scorerule" ref="scoreRuleMqListener" />
</rabbit:listener-container>
</beans>
\ No newline at end of file
... ...