springboot + elasticsearch ID自增 (AOP)

方式:AOP + 存储每个对象的最大ID

ElasticsearchSaveAop 

/**
 *  elasticsearch save
 */
@Aspect
@Configuration
public class ElasticsearchSaveAop {
	
	@Pointcut("execution(public * *..service.es..*.save(..))")
	public void exec() {};
	@Pointcut("execution(public * *..service.es..*.saveAll(..))")
	public void execAll() {};
	
	public static String esModelPackage = "com.model.es";

	@Around("exec()")
	public Object exec(ProceedingJoinPoint joinpoint) throws Throwable {
        Object ret = null;
        try {
        	Object[] args = joinpoint.getArgs();
        	setAutoId(args[0]);
        	ret = joinpoint.proceed(args);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return ret;
	}
	

	
	@Around("execAll()")
	public Object execAll(ProceedingJoinPoint joinpoint) throws Throwable {
        Object ret = null;
        try {
        	Object[] args = joinpoint.getArgs();
        	if(args[0] instanceof List) {
        		@SuppressWarnings("unchecked")
				List<Object> list = (List<Object>) args[0];
        		for(Object obj : list) {
        			setAutoId(obj);
        		}
        	}
        	ret = joinpoint.proceed(args);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return ret;
	}
	
	public void setAutoId(Object obj) {
		try {
			// 获取包下的所有类
			Set<Class<?>> clazzs = ClassUtils.getClasses(esModelPackage);
			if(clazzs != null && clazzs.size() > 0) {
				for(Class<?> clazz : clazzs) {
					if(obj.getClass().equals(clazz) && !obj.getClass().equals(SequenceId.class)) {
						setAutoId(obj, clazz);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> void setAutoId(Object obj, Class<T> clazz) {
		ElasticsearchUtil.setAutoId((T)obj, clazz);
	}
	
}

 util

/**
 * @author zhuzi
 */
public class ElasticsearchUtil {
	
	public static ElasticsearchTemplate getTemplate() {
		return SpringContextUtil.getObject(ElasticsearchTemplate .class);
	}
	
	public static SequenceIdRepository getSequenceId() {
		return SpringContextUtil.getObject(SequenceIdRepository.class);
	}
	
	private static <T> String getIdname(Class<T> clazz) {
		Field[] fs = clazz.getDeclaredFields();
		if(fs != null && fs.length > 0) {
			for(Field f : fs) {
				if(f.getAnnotation(Id.class) != null) {
					return f.getName();
				}
			}
		}
		return null;
	}

	private static <T> Class<?> getIdtype(Class<T> clazz) {
		Field[] fs = clazz.getDeclaredFields();
		if(fs != null && fs.length > 0) {
			for(Field f : fs) {
				if(f.getAnnotation(Id.class) != null) {
					return f.getType();
				}
			}
		}
		return null;
	}
	
	public static <T> T saveAutoId(T entity, ElasticsearchRepository<T, Long> repository, Class<T> clazz) {
		setAutoId(entity, clazz);
		return repository.save(entity);
	}
	
	public static <T> List<T> saveAllAutoId(List<T> entitys, ElasticsearchRepository<T, Long> repository, Class<T> clazz) {
		for(T e : entitys) {
			saveAutoId(e, repository, clazz);
		}
		return entitys;
	}
	
	private static <T> void setAutoId(T entity, Class<T> clazz) {
		Class<?> type = getIdtype(clazz);
		if(!Long.class.equals(type)) {
			return;
		}
		
		long id = getNextId(clazz.getName());
		
		String name = getIdname(clazz);
		if(name == null) {
			return;
		}
		
		Object obj = ReflectMathodUtil.getValue(entity, name);
		if(obj != null) {
			return;
		}
		
		ReflectMathodUtil.setValue(id, name, entity);
	}

	 private static long getNextId(String collName) {
		 long id = 1;
		 SequenceId seqId = null;
		 if(!getTemplate().indexExists(SequenceId.class)) {
			 getTemplate().createIndex(SequenceId.class);
		 }
		 
		 if(!getSequenceId().existsById(collName)) {
			 seqId = new SequenceId();
			 seqId.setCollName(collName);
		 } else {
			 seqId = getSequenceId().findById(collName).get();
			 id = seqId.getSeqId();
		 }
		 
		 seqId.setSeqId(id+1);
		 getSequenceId().save(seqId);
	     return id;
	}
	
}

id

@Document(indexName = "sequenceid", shards = 1,replicas = 0, refreshInterval = "-1")
@Data
public class SequenceId implements Serializable {
	private static final long serialVersionUID = 1L;
    @Id
    private String collName;
    private long seqId;
}

@Component
public interface SequenceIdRepository extends ElasticsearchRepository<SequenceId, String> {
}

示例

@Document(indexName = "test_employee", shards = 1,replicas = 0, refreshInterval = "-1")
@Data
public class EmployeeModel implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
    private Long id;
    private String firstName;
    private String lastName;
    private Integer age = 0;
    private String about;
    private Date time;
}

@Component
public interface EmployeeRepository extends ElasticsearchRepository<EmployeeModel, Long> {
}

@RestController
@RequestMapping("/es")
public class EsController {
	@Autowired
	private EmployeeRepository repository;
	
	@PostMapping("/add")
    public ApiResponse adds() {
		EmployeeModel model1 = new EmployeeModel();
		model1.setFirstName("11");
		model1.setLastName("11");
		model1.setAge(11);
		model1.setAbout("11");
		model1.setTime(new Date());
		EmployeeModel model2 = new EmployeeModel();
		model2.setFirstName("22");
		model2.setLastName("22");
		model2.setAge(22);
		model2.setAbout("22");
		model2.setTime(new Date());

		List<EmployeeModel> list = Arrays.asList(model1, model2);
		Iterable<EmployeeModel> is = ElasticsearchUtil.saveAllAutoId(list, repository, EmployeeModel.class);
		return ApiResponse.success(is);
    }

    @PostMapping("/r/adds")
    public ApiResponse addsByR() {
		EmployeeModel model1 = new EmployeeModel();
		model1.setFirstName("11");
		model1.setLastName("11");
		model1.setAge(11);
		model1.setAbout("11");
		model1.setTime(new Date());
		EmployeeModel model2 = new EmployeeModel();
		model2.setFirstName("22");
		model2.setLastName("22");
		model2.setAge(22);
		model2.setAbout("22");
		model2.setTime(new Date());

		List<EmployeeModel> list = Arrays.asList(model1, model2);
		Iterable<EmployeeModel> is = repository.saveAll(list);
		return ApiResponse.success(is);
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值