并不是所有的数据库都需要建立索引对象,同样的,也并不是所有的属性都得包含在索引对象里面
创建包index
索引接口方法
编写IndexAware接口
包括了索引的增删改查方法,后面定义的索引对象都要实现这个接口,来实现对应的增删改查方法。
package com.imooc.ad.index;
public interface IndexAware<K,V> {
V get(K key);
void add(K key,V value);
void update(K key,V value);
void delete(K key,V value);
}
建立索引对象
新建包adplan
定义AdPlanObject索引的实体类
package com.imooc.ad.index.adplan;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
//索引对象
public class AdPlanObject {
private Long planId;
private Long userId;
private Integer planStatus;
private Date startDate;
private Date endDate;
public void update(AdPlanObject newObject) {
if (null != newObject.getPlanId()) {
this.planId = newObject.getPlanId();
}
if (null != newObject.getUserId()) {
this.userId = newObject.getUserId();
}
if (null != newObject.getPlanStatus()) {
this.planStatus = newObject.getPlanStatus();
}
if (null != newObject.getStartDate()) {
this.startDate = newObject.getStartDate();
}
if (null != newObject.getEndDate()) {
this.endDate = newObject.getEndDate();
}
}
}
定义索引的实现类
定义AdPlanIndex类来实现IndexAware接口
正向索引,需要去实现之前接口定义的方法,首先要定义一个 map 的全局变量,因为 map 就是典型的 key-value 结构,符合我们的需求。由于我们的服务会实现索引的更新,而对于索引的更新,我们需要保证的就是线程安全的,于是我们需要先静态的构造一个安全的 map 全局变量。
package com.imooc.ad.index.adplan;
import com.imooc.ad.index.IndexAware;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
public class AdPlanIndex implements IndexAware<Long,AdPlanObject> {
private static Map<Long,AdPlanObject> objectMap;
static {
objectMap = new ConcurrentHashMap<>();//使用ConcurrentHashMap来实现线程安全
}
@Override
public AdPlanObject get(Long key) {
return objectMap.get(key);
}
@Override
public void add(Long key, AdPlanObject value) {
log.info("before add:{}",objectMap);
objectMap.put(key,value);
log.info("after add:{}",objectMap);
}
@Override
public void update(Long key, AdPlanObject value) {
log.info("before update:{}",objectMap);
AdPlanObject oldObject = objectMap.get(key);
if(null == oldObject){
objectMap.put(key,value);
}
else{
oldObject.update(value);
}
log.info("after update:{}",objectMap);
}
@Override
public void delete(Long key, AdPlanObject value) {
log.info("before delete:{}",objectMap);
objectMap.remove(key);
log.info("after delete:{}",objectMap);
}
}