A088_HRM_04_ Course classification cache_ course management

1. Content introduction

1. Distributed cache scheme (Master)
2. Cache service setup (Master)
3. Course classification cache (Master)
4. Course addition (mastery)

2. Course classification cache

2.1. Distributed cache scheme

2.1.1. What is caching

Usually, a copy of the data is synchronized from the database to the memory, and the client directly queries the data from the memory, which reduces the number of interactions with the database, improves the query performance (memory reads and writes quickly), and reduces the pressure on the database

2.1.2. Which data is suitable for caching

1) Frequently queried hot data
2) Infrequently changed data (data changes will cause the data in the cache to change. If it is more frequent, the performance overhead will be large)

2.1.3. Cached process

1. For the first query, check whether there is data in the cache. If not, query the data in the database. After the query is completed, json and save it to redis
2 if there is data, it indicates that there is a cache. Go directly to the cache
3 return data
1) Note: if the database data is modified, the cache should be emptied or reset; (query) when saving the data to be cached to the cache, you do not need to pay attention to whether to throw exceptions

2.1.4. Why cache course classifications

The home page of the portal needs to display the course classification. The concurrency of the home page is high, which may lead to a high probability of classification query, and the data of course classification will not change frequently. It is not necessary to query the course classification in Mysql every time. We can consider caching.

The home page of portal website is almost static html Display form.
Reason: static html Yes, it can be deployed to nginx The server.
nginx Service has two major features: 1.Only static resource deployment is supported; two.The amount of concurrency supported is very high, about tomcat 100 times the peak concurrency
2.1.5. Traditional caching scheme and process

2.1.6. Advantages and disadvantages of traditional caching schemes

1) In the cluster environment, each application has a local cache. When the cache is modified, the cache will be out of sync
2) The local cache itself takes up the memory space of the application

2.1.7. Distributed cache scheme


Redis is used as a shared cache to solve the problem of cache synchronization. Redis is an independent service, and the cache does not occupy the memory space of the application itself.

2.2. Course integration Redis

SpringBoot provides a scheme to integrate Redis. We can easily operate Redis by using the spring boot starter data Redis package

2.2.1. Import dependency
<!-- cache redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.2.2. Configure redis
spring:
  redis:
  host: localhost
  port: 6379
  timeout: 5000 #Connection timeout milliseconds
  jedis:
    pool:
      maxActive: 30
      maxIdle: 30
      minIdle: 10
      maxWait: -1 #There is no limit on the maximum waiting time of connection pool - 1
  password: 123456
2.2.3. Customize redis operation tool class
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
public class RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
//The following four overloaded methods save all the data types of value. And are stored in json format
    public void setStringKeyAndValue(String key, Object value) {
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(value));
    }

    public void setStringKeyAndValue(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public void setStringKeyAndValue(String key, Object value, long minute) {
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(value), minute, TimeUnit.MINUTES);
    }

    public void setStringKeyAndValue(String key, String value, long minute) {
        stringRedisTemplate.opsForValue().set(key, value, minute, TimeUnit.MINUTES);
    }

    /**
     * The function description takes out the object and converts it to object type
     * @param key
     * @param clazz
     * @return T
     * @author caiwen
     * @date 2020/8/22
     */
    public <T> T getKeyObjectValue(String key, Class<T> clazz) {
        T t = null;
        String s = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.equalsIgnoreCase(clazz.getName(), "java.util.lang.string")) {
            t = (T) s;
        } else if (StringUtils.isNotBlank(s)) {
            t = JSONObject.parseObject(s, clazz);
        }
        return t;
    }
}

2.3. Course classification implementation cache

2.3.1. Course classification cache logic

What are the characteristics of technology? What's the usage? What can solve my problem
How do I use it? What functions does it provide? What are the common API methods?
Actual combat - solve practical problems?

1. Query whether there is a course classification in Redis
2. If yes, retrieve Redis data, perform TreeData processing and return
3. If not, query the course classification from Mysql
4. Classify and store courses in Redis
5. Classify the courses for TreeData processing and return them

Code slightly
2.3.2. Course classification cache clearing

The course classification in the database is modified, deleted and added. The course classification in Redis needs to be cleared or reset, otherwise it will cause inconsistency between the cached data and the database data. For example:

@Override
//Delete cache
public boolean insert(CourseType entity) {
    boolean insert = super.insert(entity);
    redisTemplate.delete(RedisConstants.KEY_COURSE_TYPE_TREE);
    return insert;
}

2.4. Using spring cache to implement caching

For cache declarations, Spring's cache provides a set of java annotations:
'@ Cacheable': trigger cache write.
'@ CacheEvict': trigger cache cleanup.
▶ @ CachePut: update the cache (it will not affect the operation of the method).
▶ @ Caching: recombine multiple cache operations to be applied to the method.
'@ CacheConfig': set some common cache settings shared at the class level.

See the document Springboot integrated Cache Redis based Cache.docx for specific usage

2.4.1. Open SpringCache
//Cache service
@SpringBootApplication
@EnableCaching
public class CacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class) ;
    }
}
2.4.2. Course classification cache
@Override
@Cacheable(cacheNames = RedisConstants.KEY_COURSE_TYPE_TREE,key = "'ALL'")
public List<CourseType> treeData() {
    log.debug("From data

Library query course classification..........................");
    return treeDataMethodThree();
}
2.4.3. Cache deletion
@Override
@CacheEvict(cacheNames = RedisConstants.KEY_COURSE_TYPE_TREE,key = "'ALL'")
public boolean insert(CourseType entity) {
    return super.insert(entity);
}
@Override
@CacheEvict(cacheNames = RedisConstants.KEY_COURSE_TYPE_TREE,key = "'ALL'")
public boolean deleteById(Serializable id) {
    return super.deleteById(id);
}
@Override
@CacheEvict(cacheNames = RedisConstants.KEY_COURSE_TYPE_TREE,key = "'ALL'")
public boolean updateById(CourseType entity) {
    return super.updateById(entity);
}

3. Course management

3.1. curriculum design

3.1.1. Course page design
  1. Course list
    Add a course and enter the course data into the database
    Course marketing, configure marketing information such as course price
    Upload resources and add photo album information of the course
    Course publishing, also known as course online, can only be displayed on the portal after publishing, which is based on ES
    Courses that are offline and cancelled course publishing cannot be displayed to the portal
  2. New courses
    Enter basic course information
    Enter course marketing
    Enter course details

    The data here needs to be saved to three tables, and the basic information needs to be saved to t_course, save marketing information to t_course_marker, save course details to t_course_detail
3.1.2. Curriculum design

Vertical classification of courses according to different dimensions
T_course saves basic course information
T_course_resource saves course resources, such as photo albums
T_course_market save course marketing information
T_course_detail save course details

3.2. Basic course management

3.2.1. Basic code generation
3.2.2. Course CRUD implementation

3.3. Course addition

We have analyzed the layout of adding pop-up window above. We need to add the data of one form to three tables
t_course: course schedule
t_course_detail: course details
t_course_market: course marketing table
t_course_resource: course resource table, which can upload course resources (course album) separately through the "upload resources" button

Supplement: add one in the children field of CourseType
@JsonInclude(JsonInclude.Include.NON_EMPTY): null value fields are not processed when converting to JSON

3.3.1. Submission and addition of previous paragraph

Parameter format

var param = {
                course:{
                    courseTypeId:this.addForm.courseTypeId,
                    name:this.addForm.name,
                    users:this.addForm.users,
                    grade:this.addForm.gradeId,
                    gradeName:gradeName,
                    pic:this.addForm.pic,
                    startTime:this.addForm.startTime,
                    endTime:this.addForm.endTime
   },
               courseDetail:{
                    description:this.addForm.description,
                    intro:this.addForm.intro
   },
               courseMarket:{
                    charge:this.addForm.chargeId,
                    qq:this.addForm.qq,
                    price:this.addForm.price,
                    priceOld:this.addForm.priceOld,
                    expires:this.addForm.expires
   }
};
3.3.2. Parameter DTO encapsulation
//Encapsulating parameters added to the course
public class CourseSaveDto {
    private Course course;
    private CourseDetail courseDetail;
    private CourseMarket courseMarket;
3.3.3. Add controller to the course
/**
* Save and modify public
* @return Ajaxresult Conversion results
*/
@RequestMapping(value="/saveOrUpdate",method= RequestMethod.POST)
public AjaxResult saveOrUpdate(@RequestBody CourseSaveDto courseDto){
    try {
        courseService.saveOrUpdate(courseDto);
        return AjaxResult.me();
    } catch (Exception e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("Failed to save object!"+e.getMessage());
    }
}
3.3.4. Add service to the course
@Override
public void saveOrUpdate(CourseSaveDto courseDto) {
    Course course = courseDto.getCourse();
    CourseDetail courseDetail = courseDto.getCourseDetail();
    CourseMarket courseMarket = courseDto.getCourseMarket();
    //1. Basic judgment
    //2. Save course
    course.setStatus(Course.STATUS_OFFLINE);
    course.setUserId(42l);
    course.setUserName("yhptest1");
    course.setTenantId(26l);
    course.setTenantName("Source code Era");
    baseMapper.insert(course);
    //3. Save details
    courseDetail.setId(course.getId());

    courseDetailMapper.insert(courseDetail);

    //4. Save marketing
    courseMarket.setId(course.getId());
    courseMarketMapper.insert(courseMarket);
}

Note: the ID of course marketing courseMarket and course details courseDetail uses the ID of course. The user and organization who created the course are temporarily dead because they have not logged in yet.

4. Course summary

4.1. a key

1.Redis cache
2. Course addition

4.2. Interview questions

1. Cached query process

Keywords: Java

Added by mattnoble on Sun, 23 Jan 2022 21:00:13 +0200