微服务项目 -- day02 微服务的查询与缓存

一、招聘微服务开发


1、表结构分析




2、代码生成


使用代码生成器生成招聘微服务代码,代码生成器地址:https://download.csdn.net/download/wingzhezhe/10533525


(1)、使用代码生成器生成代码




(2)、将生成的招聘微服务的代码直接拷入到IDEA工作空间中




(3)、修改scf_parent的pom.xml文件,引入子模块




3、修改招聘微服务的主配置文件及启动引导类


application.yml


server: 
  port: 9002
spring: 
  application:  
    name: scf-recruit #指定服务名
  datasource:  
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.37.133:3306/tensquare_recruit?characterEncoding=UTF8
    username: root
    password: 123456
  jpa: 
    database: MySQL
    show-sql: true




4、热门企业列表功能


(1)、EnterpriseDao.java


    /**
     * 使用JPA给定格式进行条件查询
     * @param isHot 是否热门
     * @return
     */
    public List<Enterprise> findByIshot(String isHot);


(2)、EnterpriseService.java


	/**
	 * 查询热门企业列表
	 * @param isHot
	 * @return
	 */
	public List<Enterprise> findByIshot(String isHot){
		return enterpriseDao.findByIshot(isHot);
	}


(3)、EnterpriseController.java


    /**
     * 查询热门企业列表
     *
     * @return
     */
    @RequestMapping(value = "/search/hotlist", method = RequestMethod.GET)
    public Result findHotlist() {
        List<Enterprise> enterpriseList = enterpriseService.findByIshot("1");
        return new Result(true, StatusCode.OK, "查询成功", enterpriseList);
    }


5、推荐职位列表功能


(1)、RecruitDao.java


    /**
     * 按照JPA格式,按状态根据日期倒叙查询前4条数据
     * Top4 : 查询前4个
     * OrderBy : 排序
     * Desc : 倒序
     * @param state
     * @return
     */
    public List<Recruit> findTop4ByStateOrderByCreatetimeDesc(String state);


(2)、RecruitService.java


	/**
	 * 根据状态查询列表
	 * @param state
	 * @return
	 */
	public List<Recruit> findByState(String state){
		return recruitDao.findTop4ByStateOrderByCreatetimeDesc(state);
	}


(3)、RecruitController.java


	/**
	 * 查询推荐
	 * @return
	 */
	@RequestMapping(value = "/search/recommend", method = RequestMethod.GET)
	public Result getRecommend(){
		List<Recruit> recruitList = recruitService.findByState("2");
		return new Result(true, StatusCode.OK, "查询成功", recruitList);
	}


6、最新职位列表功能


(1)、RecruitDao.java


    /**
     * 查询状态不为参数的数据列表
     * ByStateNot : 相当于查询值不等于state的值的数据
     * @param state
     * @return
     */
    public List<Recruit> findTop2ByStateNotOrderByCreatetimeDesc(String state);


(2)、RecruitService.java


	/**
	 * 查询最新职位列表
	 * @return
	 */
	public List<Recruit> findNewList(){
		return recruitDao.findTop2ByStateNotOrderByCreatetimeDesc("2");
	}


(3)、RecruitController.java


	/**
	 * 查询最新职位列表
	 * @return
	 */
	@RequestMapping(value = "/search/newlist", method = RequestMethod.GET)
	public Result findNewList(){
		List<Recruit> recruitList = recruitService.findNewList();
		return new Result(true, StatusCode.OK, "查询成功", recruitList);
	}


二、问答微服务开发


1、表结构




2、使用代码生成器生成代码并导入项目中


(1)、本次使用的表为tensquare_qa表


(2)、修改tomcat端口号9003,修改连接数据库的url


(3)、修改启动类名称


3、加入问题标签中间表实体类


package com.scf.qa.pojo;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

/**
 * 问题标签中间表实体类
 */
@Entity
@Table(name = "tb_pl")
public class Pl implements Serializable {
    @Id
    private String problemid;   //问题ID
    @Id
    private String labelid;     //标签ID

    public Pl(String problemid, String labelid) {
        this.problemid = problemid;
        this.labelid = labelid;
    }

    public Pl() {

    }

   getter/setter
}


4、最新回答列表、热门回答列表、等待回答列表功能实现


(1)、ProblemDao.java


    /**
     * 使用JPQL语法查询最新回答列表数据
     * @param labelId
     * @param pageable
     * @return
     */
    @Query("select p from Problem p where id in (select problemid from Pl where labelid = ?1) order by p.replytime desc")
    public Page<Problem> findNewListByLabelId(String labelId, Pageable pageable);

    /**
     * 使用JPQL语法查询热门回答列表数据
     * @param labelId
     * @param pageable
     * @return
     */
    @Query("select p from Problem p where id in (select problemid from Pl where labelid = ?1) order by p.reply desc")
    public Page<Problem> findHotListByLabelId(String labelId, Pageable pageable);

    /**
     * 使用JPQL语法查询等待回答列表数据
     * @param labelId
     * @param pageable
     * @return
     */
    @Query("select p from Problem p where id in (select problemid from Pl where labelid = ?1) and p.reply=0 order by p.createtime desc")
    public Page<Problem> findWaitListByLabelId(String labelId, Pageable pageable);


(2)、ProblemService.java


	/**
	 * 最新回答列表查询
	 * @param labelId
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<Problem> findNewListByLabelId(String labelId, int page, int size){
		PageRequest pageRequest = PageRequest.of(page - 1, size);
		return problemDao.findNewListByLabelId(labelId, pageRequest);
	}

	/**
	 * 热门回答列表查询
	 * @param labelId
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<Problem> findHotListByLabelId(String labelId, int page, int size){
		PageRequest pageRequest = PageRequest.of(page - 1, size);
		return problemDao.findHotListByLabelId(labelId, pageRequest);
	}

	/**
	 * 等待回答列表查询
	 * @param labelId
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<Problem> findWaitListByLabelId(String labelId, int page, int size){
		PageRequest pageRequest = PageRequest.of(page - 1, size);
		return problemDao.findWaitListByLabelId(labelId, pageRequest);
	}


(3)、ProblemController.java


    /**
     * 查询等待回答列表
     *
     * @param label
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/waitlist/{label}/{page}/{size}", method = RequestMethod.GET)
    public Result findWaitListByLabelId(@PathVariable String label, @PathVariable int page, @PathVariable int size) {
        Page<Problem> pageList = problemService.findWaitListByLabelId(label, page, size);
        PageResult pageResult = new PageResult(pageList.getTotalElements(), pageList.getContent());
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    /**
     * 查询最新回答列表
     *
     * @param label
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/newlist/{label}/{page}/{size}", method = RequestMethod.GET)
    public Result findNewListByLabelId(@PathVariable String label, @PathVariable int page, @PathVariable int size) {
        Page<Problem> pageList = problemService.findNewListByLabelId(label, page, size);
        PageResult pageResult = new PageResult(pageList.getTotalElements(), pageList.getContent());
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    /**
     * 查询最新回答列表
     *
     * @param label
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/hotlist/{label}/{page}/{size}", method = RequestMethod.GET)
    public Result findHotListByLabelId(@PathVariable String label, @PathVariable int page, @PathVariable int size) {
        Page<Problem> pageList = problemService.findHotListByLabelId(label, page, size);
        PageResult pageResult = new PageResult(pageList.getTotalElements(), pageList.getContent());
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }


三、文章微服务开发


1、表结构




2、代码生成


代码生成同上


3、文章审核、文章点赞功能实现


(1)、ArticleDao.java


    /**
     * 文章审核功能
     * @param id
     */
    @Modifying
    @Query("update Article set state='1' where id=?1")
    public void examine(String id);

    /**
     * 文章点赞功能
     * @param id
     */
    @Modifying
    @Query("update Article set thumbup=thumbup+1 where id=?1")
    public void updateThumbup(String id);


(2)、ArticleService.java


	/**
	 * 文章审核功能
	 * @param id
	 */
	@Transactional
	public void examine(String id){
		articleDao.examine(id);
	}

	/**
	 * 文章审核功能
	 * @param id
	 */
	@Transactional
	public void updateThumbup(String id){
		articleDao.updateThumbup(id);
	}


(3)、ArticleController.java


	/**
	 * 文章审核功能
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/examine/{id}", method = RequestMethod.PUT)
	public Result examine(@PathVariable String id){
		articleService.examine(id);
		return new Result(true,StatusCode.OK,"审核成功");
	}

	/**
	 * 文章点赞功能
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/thumbup/{id}", method = RequestMethod.PUT)
	public Result thumbup(@PathVariable String id){
		articleService.updateThumbup(id);
		return new Result(true,StatusCode.OK,"点赞成功");
	}


四、缓存处理


1、Redis环境搭建


(1)、创建redis容器


docker run -di --name=tensquare_redis -p 6379:6379 redis


(2)、scf_acticle项目中引入springdataRedis的jar包坐标


	<!-- 引入spirng-data-redis的jar包坐标 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>


(3)、application.yml中加入redis配置




2、实现文章缓存处理


ArticleService.java


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Article findById(String id) {
        //先从redis中查询,如果没有,再从数据库中查询,并将结果放入redis中
        Article article = (Article) redisTemplate.opsForValue().get("article_" + id);
        if (article == null) {
            //从数据库中查询数据,放入缓存中,并设置过期时间
            article = articleDao.findById(id).get();
            redisTemplate.opsForValue().set("article_" + id, article, 1, TimeUtil.DAYS);
        }
        return article;
    }

    /**
     * 修改
     *
     * @param article
     */
    public void update(Article article) {
        //文章修改后从redis中删除文章数据
        redisTemplate.delete("article_" + article.getId());
        articleDao.save(article);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {

        //文章修改后从redis中删除文章数据
        redisTemplate.delete("article_" + id);
        articleDao.deleteById(id);
    }


3、Spring Cache


springboot提供的缓存,详见:https://blog.csdn.net/wingzhezhe/article/details/78434268 中springboot-redis的应用


4、活动微服务中的活动信息的缓存处理


(1)、使用代码生成器生成项目代码


scf_gathering


(2)、导入项目,进行配置文件等的配置


配置tomcat端口号、redis配置、导入redis坐标、修改启动引导类名称


(3)、活动微服务中的缓存保存于清除


GathringApplication.java


package com.scf.gathering;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import util.IdWorker;

@SpringBootApplication
@EnableCaching //该注解作用是开启springboot对缓存注解的支持
public class GatheringApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatheringApplication.class, args);
    }

    @Bean
    public IdWorker idWorkker() {
        return new IdWorker(1, 1);
    }

}


GathringService.java


    /**
     * 根据ID查询实体
     * 将查询的数据存入缓存中
     * value : 缓存的名称
     * key	:	对应的key值,#id表示直接获取参数中的id变量的值
     *
     * @param id
     * @return
     */
    @Cacheable(value = "gathering", key = "#id")
    public Gathering findById(String id) {
        return gatheringDao.findById(id).get();
    }
    

    /**
     * 修改
     * 修改后要删除缓存中的数据
     *
     * @param gathering
     */
    @CacheEvict(value = "gathring", key = "#gathering.id")
    public void update(Gathering gathering) {
        gatheringDao.save(gathering);
    }

    
    /**
     * 删除
     *
     * @param id
     */
    @CacheEvict(value = "gathring", key = "#gathering.id")
    public void deleteById(String id) {
        gatheringDao.deleteById(id);
    }



猜你喜欢

转载自blog.csdn.net/wingzhezhe/article/details/80984228