![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/dcdd1feb43a8316e35c00baf8e6808a9.png#pic_center)
废话不多说 直接上后端代码
package com.jsy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.jsy.dao")
public class SpringBootEsRedisApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootEsRedisApp.class,args);
}
}
- 实体类 项目索引project类 和年份投资值projectInput类 一个项目对应多个年份的投资值
package com.jsy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Document(indexName = "jhtlproject",type = "project")
public class Project implements Serializable {
@Id
private String projectId;
@Field(type = FieldType.Keyword)
private String projectName;
@Field(type = FieldType.Keyword)
private String buildNature;
@Field(type = FieldType.Keyword)
private String affiliatedUnit;
private List<ProjectInput> inputList;
@Field(type = FieldType.Keyword)
private String projectTime;
@Field(type = FieldType.Double)
private Double projectPrice;
}
server.port=9999
server.servlet.context-path=/EsWeb
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jhtlproject?characterEncoding=utf-8
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.type-aliases-package=com.jsy.entity
mybatis.mapper-locations=classpath:com/jsy
package com.jsy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class ProjectInput implements Serializable {
private String inputId;
private String projectTime;
private Double projectPrice;
private String inputName;
}
package com.jsy.controller;
import com.jsy.entity.Project;
import com.jsy.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
import java.util.List;
@RestController
@RequestMapping("/projectController")
public class ProjectController {
@Autowired
private ProjectService projectService;
@GetMapping(value = "/queryProjectByPage")
public List<Project> queryProjectByPage(@RequestParam(value = "page", defaultValue = "1") Integer pageNow,
@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
@RequestParam(value = "projectId" ) String projectId,
@RequestParam(value = "projectName") String projectName,
@RequestParam(value = "buildNature") String buildNature,
@RequestParam(value = "affiliatedUnit") String affiliatedUnit,
@RequestParam(value = "projectTime") String projectTime){
List<Project> projectList = projectService.queryProjectByPage(pageNow,pageSize,projectId,projectName,buildNature,affiliatedUnit,projectTime);
return projectList;
}
@GetMapping(value = "/queryProjectCount")
public Integer queryProjectCount(@RequestParam(value = "projectId" ) String projectId,
@RequestParam(value = "projectName") String projectName,
@RequestParam(value = "buildNature") String buildNature,
@RequestParam(value = "affiliatedUnit") String affiliatedUnit,
@RequestParam(value = "projectTime") String projectTime) {
int queryProjectCount = projectService.queryProjectCount(projectId,projectName,buildNature,affiliatedUnit,projectTime);
return queryProjectCount;
}
@GetMapping(value = "/queryTotalSum")
public Double queryTotalSum(@RequestParam(value = "projectId" ) String projectId,
@RequestParam(value = "projectName") String projectName,
@RequestParam(value = "buildNature") String buildNature,
@RequestParam(value = "affiliatedUnit") String affiliatedUnit,
@RequestParam(value = "projectTime") String projectTime){
Double aDouble = projectService.queryTotalSum(projectId, projectName, buildNature, affiliatedUnit, projectTime);
return aDouble;
}
@GetMapping(value = "/existsProject")
public Boolean queryUserById(Project project) {
return projectService.queryProjectByName(project.getProjectName());
}
@PostMapping(value = "/addProject")
@ResponseBody
public void addProject(@RequestPart(value = "project") Project project) {
projectService.addProject(project);
}
@PutMapping(value = "/updateProject")
@ResponseBody
public void updateProject(@RequestPart(value = "project") Project project){
System.out.println("updateProject project = " + project);
projectService.updateProject(project);
}
@PutMapping(value = "/updateProjectPrice")
@ResponseBody
public void updateProjectPrice(@RequestPart(value = "project") Project project){
System.out.println("updateProjectPrice project = " + project);
projectService.updateProjectInput(project);
}
@GetMapping(value = "/queryAllProjectAffiliatedUnit")
@ResponseBody
public HashSet<String> queryAllProjectAffiliatedUnit(){
HashSet<String> stringHashSet = projectService.queryAllProjectAffiliatedUnit();
return stringHashSet;
}
}
- es的ElasticsearchRepository工具
package com.jsy.es.repsitory;
import com.jsy.entity.Project;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ProjectRespository extends ElasticsearchRepository<Project,String> {
public Project findByProjectName(String projectName);
}
- es工具类TransportClient 用来做java操作
package com.jsy.es.conf;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Configuration
public class EsConf {
@Bean
public TransportClient getTransportClient() throws UnknownHostException {
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.17.216"),9300));
return transportClient;
}
}
package com.jsy.es.conf;
import io.netty.util.internal.StringUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
public class BoolQueryBuilderConf {
public static BoolQueryBuilder getBoolQueryBuilder(String projectId,String projectName,String buildNature,String affiliatedUnit){
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if (!StringUtil.isNullOrEmpty(projectId)) {
boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("projectId",projectId));
}
if (!StringUtil.isNullOrEmpty(projectName)) {
boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("projectName",projectName));
}
if (!StringUtil.isNullOrEmpty(buildNature)) {
boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("buildNature",buildNature));
}
if (!StringUtil.isNullOrEmpty(affiliatedUnit)) {
boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("affiliatedUnit",affiliatedUnit));
}
return boolQueryBuilder;
}
}
package com.jsy.service;
import com.jsy.entity.Project;
import com.jsy.entity.ProjectInput;
import org.springframework.data.repository.query.Param;
import java.util.HashSet;
import java.util.List;
public interface ProjectService {
List<Project> queryProjectByPage(
@Param(value = "pageNow") Integer pageNow,
@Param(value = "pageSize") Integer pageSize,
@Param(value = "projectId" ) String projectId,
@Param(value = "projectName") String projectName,
@Param(value = "buildNature") String buildNature,
@Param(value = "affiliatedUnit") String affiliatedUnit,
@Param(value = "projectTime") String projectTime
);
Double queryTotalSum(String projectId, String projectName, String buildNature, String affiliatedUnit, String projectTime);
int queryProjectCount(@Param(value = "projectId" ) String projectId,
@Param(value = "projectName") String projectName,
@Param(value = "buildNature") String buildNature,
@Param(value = "affiliatedUnit") String affiliatedUnit,
@Param(value = "projectTime") String projectTime);
HashSet<String> queryAllProjectAffiliatedUnit();
Boolean queryProjectByName(String projectName);
void addProject(Project project);
void updateProject(Project project);
void updateProjectInput(Project project);
}
package com.jsy.service.impl;
import com.jsy.dao.InputDao;
import com.jsy.dao.ProjectDao;
import com.jsy.entity.ProjectInput;
import com.jsy.es.conf.BoolQueryBuilderConf;
import com.jsy.entity.Project;
import com.jsy.es.repsitory.ProjectRespository;
import com.jsy.service.ProjectService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {
@Resource
TransportClient transportClient;
@Autowired
ProjectRespository projectRespository;
@Autowired
RedisTemplate<Object, Project> redisTemplate;
@Resource
ProjectDao projectDao;
@Resource
InputDao inputDao;
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public List<Project> queryProjectByPage(Integer pageNow, Integer pageSize, String projectId, String projectName, String buildNature, String affiliatedUnit, String projectTime) {
PageRequest pageRequest = PageRequest.of(pageNow - 1, pageSize);
BoolQueryBuilder boolQueryBuilder = BoolQueryBuilderConf.getBoolQueryBuilder(projectId, projectName, buildNature, affiliatedUnit);
List<Project> projectList = projectRespository.search(boolQueryBuilder, pageRequest).getContent();
ArrayList<Project> ArrayList = new ArrayList<>();
if (projectList.size() > 0) {
for (Project project : projectList) {
Project addArrayListProject;
addArrayListProject = projectDao.queryOneProjectFromMySql(project.getProjectId());
ProjectInput queryProjectPriceSumById = new ProjectInput();
queryProjectPriceSumById.setInputId(project.getProjectId());
List<ProjectInput> projectInputList = inputDao.queryProjectInputByMySql(queryProjectPriceSumById);
double sum = 0.00;
for (ProjectInput projectInput : projectInputList) {
if (projectTime==""){
sum += projectInput.getProjectPrice();
}else if (projectInput.getProjectTime().equals(projectTime)){
sum=projectInput.getProjectPrice();
}
}
addArrayListProject.setProjectPrice(sum);
ArrayList.add(addArrayListProject);
}
}
return ArrayList;
}
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public Double queryTotalSum(String projectId, String projectName, String buildNature, String affiliatedUnit, String projectTime) {
BoolQueryBuilder boolQueryBuilder = BoolQueryBuilderConf.getBoolQueryBuilder(projectId, projectName, buildNature, affiliatedUnit);
Iterator<Project> iterator = projectRespository.search(boolQueryBuilder).iterator();
double totalSum = 0.00;
while (iterator.hasNext()) {
String s = iterator.next().getProjectId();
List<ProjectInput> projectInputList = inputDao.queryProjectInputByMySql(new ProjectInput(s, projectTime, null, null));
for (ProjectInput projectInput : projectInputList) {
totalSum += projectInput.getProjectPrice();
}
}
return totalSum;
}
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public int queryProjectCount(String projectId, String projectName, String buildNature, String affiliatedUnit, String projectTime) {
BoolQueryBuilder boolQueryBuilder = BoolQueryBuilderConf.getBoolQueryBuilder(projectId, projectName, buildNature, affiliatedUnit);
SearchResponse searchResponse = transportClient.prepareSearch("jhtlproject")
.setTypes("project")
.setQuery(boolQueryBuilder)
.get();
Long totalHits = searchResponse.getHits().getTotalHits();
int intValue = totalHits.intValue();
return intValue;
}
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public Boolean queryProjectByName(String projectName) {
Project byProjectName = projectRespository.findByProjectName(projectName);
if (byProjectName == null) {
return false;
} else {
return true;
}
}
@Override
public void addProject(Project project) {
String yyyyMMddhhmmss = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).substring(2);
project.setProjectId(yyyyMMddhhmmss);
ProjectInput projectInput = new ProjectInput(yyyyMMddhhmmss, project.getProjectTime(), project.getProjectPrice(), project.getProjectName());
projectDao.insertProjectToMySql(project);
inputDao.insertProjectInputToMySql(projectInput);
projectRespository.save(project);
redisTemplate.opsForSet().add(project.getProjectTime(), project);
}
@Override
public void updateProject(Project project) {
System.out.println("imp updateProject---+++project = " + project);
projectDao.updateProjectToMySql(project);
projectRespository.save(project);
}
@Override
public void updateProjectInput(Project project) {
System.out.println("imp updateProjectInput---+++project = " + project);
ProjectInput projectInput = new ProjectInput(project.getProjectId(), project.getProjectTime(), project.getProjectPrice(), project.getProjectName());
List<ProjectInput> projectInputList = inputDao.queryProjectInputByMySql(projectInput);
Boolean flog = true;
for (ProjectInput input : projectInputList) {
if (project.getProjectTime()!=""&&input.getProjectTime().equals(project.getProjectTime())) {
inputDao.updateProjectInputToMySql(projectInput);
flog = false;
}
}
if (flog) {
inputDao.insertProjectInputToMySql(projectInput);
}
}
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public HashSet<String> queryAllProjectAffiliatedUnit() {
Iterable<Project> all = projectRespository.findAll();
Iterator<Project> iterator = all.iterator();
HashSet<String> queryAllProjectAffiliatedUnitSet = new HashSet<>();
while (iterator.hasNext()) {
queryAllProjectAffiliatedUnitSet.add(iterator.next().getAffiliatedUnit());
}
return queryAllProjectAffiliatedUnitSet;
}
}
package com.jsy.dao;
import com.jsy.entity.Project;
public interface ProjectDao {
Project queryOneProjectFromMySql(String projectId);
void insertProjectToMySql(Project project);
void updateProjectToMySql(Project project);
}
package com.jsy.dao;
import com.jsy.entity.ProjectInput;
import java.util.List;
public interface InputDao {
void insertProjectInputToMySql(ProjectInput projectInput);
void updateProjectInputToMySql(ProjectInput projectInput);
List<ProjectInput> queryProjectInputByMySql(ProjectInput projectInput);
}
<?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.jsy.dao.ProjectDao">
<cache type="com.jsy.cache.ProjectDefineRedisCache">
<property name="timeout" value="60"/>
</cache>
<resultMap type="com.jsy.entity.Project" id="ProjectMap">
<id property="projectId" column="projectId" jdbcType="VARCHAR"/>
<result property="projectName" column="projectName" jdbcType="VARCHAR"/>
<result property="buildNature" column="buildNature" jdbcType="VARCHAR"/>
<result property="affiliatedUnit" column="affiliatedUnit" jdbcType="VARCHAR"/>
<collection property="inputList" ofType="com.jsy.entity.ProjectInput">
<result property="inputId" column="inputId"/>
<result property="projectTime" column="projectTime"/>
<result property="projectPrice" column="projectPrice"/>
<result property="inputName" column="inputName"/>
</collection>
</resultMap>
<!--查询项目-->
<select id="queryOneProjectFromMySql" resultMap="ProjectMap" resultType="com.jsy.entity.Project">
select
projectId, projectName, buildNature, affiliatedUnit,inputId,projectTime,projectPrice,inputName
from project p join input i
on p.projectId=i.inputId
where projectId=#{projectId}
</select>
<!--添加项目主要索引-->
<insert id="insertProjectToMySql" parameterType="com.jsy.entity.Project">
insert into project(projectId,projectName,buildNature,affiliatedUnit)
values (#{projectId},#{projectName},#{buildNature},#{affiliatedUnit})
</insert>
<!--修改项目主要索引-->
<update id="updateProjectToMySql" parameterType="com.jsy.entity.Project">
update project
set projectName=#{projectName},buildNature=#{buildNature},affiliatedUnit=#{affiliatedUnit}
where projectId = #{projectId}
</update>
</mapper>
<?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.jsy.dao.InputDao">
<resultMap type="com.jsy.entity.ProjectInput" id="pinput">
<result property="inputId" column="inputId" jdbcType="VARCHAR"/>
<result property="projectTime" column="projectTime" jdbcType="VARCHAR"/>
<result property="projectPrice" column="projectPrice" jdbcType="NUMERIC"/>
<result property="inputName" column="inputName" jdbcType="VARCHAR"/>
</resultMap>
<!--查询项目年份计划值-->
<select id="queryProjectInputByMySql" resultMap="pinput">
select
inputId,projectTime,projectPrice,inputName
from input
<where>
<if test="inputId != null and inputId != ''">
and inputId = #{inputId}
</if>
<if test="projectTime != null and projectTime != ''">
and projectTime = #{projectTime}
</if>
</where>
</select>
<!--添加项目年份计划值-->
<insert id="insertProjectInputToMySql" parameterType="com.jsy.entity.ProjectInput">
insert into input(inputId,projectTime,projectPrice,inputName)
values (#{inputId},#{projectTime},#{projectPrice},#{inputName})
</insert>
<!--修改项目-->
<update id="updateProjectInputToMySql" parameterType="com.jsy.entity.ProjectInput">
update input
set projectPrice=#{projectPrice}
<where>
<if test="inputId != null and inputId != ''">
and inputId = #{inputId}
</if>
<if test="projectTime != null and projectTime != ''">
and projectTime = #{projectTime}
</if>
</where>
</update>
</mapper>
package com.jsy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext=null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
}
package com.jsy.cache;
import com.jsy.entity.Project;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
@Configuration
public class RedisConf {
@Bean
public RedisTemplate<Object, Project> getProjectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Project> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Project> serializer = new Jackson2JsonRedisSerializer<Project>(Project.class);
redisTemplate.setDefaultSerializer(serializer);
return redisTemplate;
}
}
package com.jsy.cache;
import com.jsy.ApplicationContextHolder;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ProjectDefineRedisCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(ProjectDefineRedisCache.class);
private String id;
private long timeout=300;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private RedisTemplate redisTemplate;
public ProjectDefineRedisCache(String id){
this.id=id;
}
private RedisTemplate getRedisTemplate(){
return (RedisTemplate) ApplicationContextHolder.getBean("redisTemplate");
}
@Override
public String getId() {
return id;
}
@Override
public void putObject(Object key, Object value) {
if(redisTemplate==null){
redisTemplate=getRedisTemplate();
}
logger.debug("将查询结果缓存到Redis--cache.key"+key+"\tvalue"+value);
ValueOperations opsForValue = redisTemplate.opsForValue();
opsForValue.set(key, value, 10, TimeUnit.MINUTES);
}
@Override
public Object getObject(Object key) {
if(redisTemplate==null){
redisTemplate=getRedisTemplate();
}
logger.debug("获取缓存结果"+key);
ValueOperations opsForValue = redisTemplate.opsForValue();
return opsForValue.get(key);
}
@Override
public Object removeObject(Object key) {
if(redisTemplate==null){
redisTemplate=getRedisTemplate();
}
logger.debug("删除Redis中的Key:"+key);
ValueOperations opsForValue = redisTemplate.opsForValue();
Object value = opsForValue.get(key);
redisTemplate.delete(key);
return value;
}
@Override
public void clear() {
if(redisTemplate==null){
redisTemplate=getRedisTemplate();
}
logger.debug("删除所有Redis中的缓存");
redisTemplate.execute((RedisCallback) connection -> {
connection.flushDb();
return null;
});
}
@Override
public int getSize() {
return 0;
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
}