文章目录
课程类型数据查询
1.如何查询数据
先查到所有数据,再根据条件封装(在Java代码中),也可以通过配置mybatis sql语句来实现
2.如何封装数据
- 遍历集合,如果pid为0,即为父,封装到一个list中
- 如果pid不为0,即为子,则在此基础上再遍历一次集合,拿到与对应的父,将子add进父
ArrayList<CourseType> pcourseTypes = new ArrayList<>();
for (CourseType courseType : courseTypes) {
if (courseType.getPid() == 0) {
pcourseTypes.add(courseType);
}
if (courseType.getPid() != 0) {
CourseType tempCourseType = null;
for (CourseType type : courseTypes) {
if (type.getId().equals(courseType.getPid())) {
tempCourseType = type;
break;
}
}
if (tempCourseType != null) {
tempCourseType.getChildren().add(courseType);
}
}
}
3.配置跨域
在zuul加个配置文件
package myllxy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
config.addAllowedOrigin("http://127.0.0.1:6001");
config.addAllowedOrigin("http://localhost:6001");
//2) 是否发送Cookie信息
config.setAllowCredentials(true);
//3) 允许的请求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允许的头信息
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new
UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
给课程分类做缓存
1.简介
本质:将经常查询的数据放到redis中,减轻数据库的压力,加快数据响应速度
将redis与服务集成在一起的话会面临以下问题:
- 和服务本身抢占资源
- 在集群中多个应用的缓存不一样需要同步缓存,加大了开销
于是有了分布式redis缓存即中央缓存解决了以上问题
2.搭建基础服务
3.集成redis
1.导包
<dependency>
<groupId>myllxy</groupId>
<artifactId>hrm-basic-utils</artifactId>
</dependency>
2.工具类
package myllxy.redis.utils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.util.Properties;
/**
* 获取连接池对象
*/
public enum RedisUtils {
INSTANCE;
static JedisPool jedisPool = null;
static {
//1 创建连接池配置对象
JedisPoolConfig config = new JedisPoolConfig();
//2 进行配置-四个配置
config.setMaxIdle(1);//最小连接数
config.setMaxTotal(11);//最大连接数
config.setMaxWaitMillis(10 * 1000L);//最长等待时间
config.setTestOnBorrow(true);//测试连接时是否畅通
//3 通过配置对象创建连接池对象
Properties properties = null;
try {
properties = new Properties();
properties.load(RedisUtils.class.getClassLoader().getResourceAsStream("redis.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String host = properties.getProperty("redis.host");
String port = properties.getProperty("redis.port");
String password = properties.getProperty("redis.password");
String timeout = properties.getProperty("redis.timeout");
jedisPool = new JedisPool(config, host, Integer.valueOf(port), Integer.valueOf(timeout), password);
}
//获取连接
public Jedis getSource() {
return jedisPool.getResource();
}
//关闭资源
public void closeSource(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
/**
* 设置字符值
*
* @param key
* @param value
*/
public void set(String key, String value) {
Jedis jedis = getSource();
jedis.set(key, value);
closeSource(jedis);
}
/**
* 设置
*
* @param key
* @param value
*/
public void set(byte[] key, byte[] value) {
Jedis jedis = getSource();
jedis.set(key, value);
closeSource(jedis);
}
/**
* @param key
* @return
*/
public byte[] get(byte[] key) {
Jedis jedis = getSource();
try {
return jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeSource(jedis);
}
return null;
}
/**
* 设置字符值
*
* @param key
*/
public String get(String key) {
Jedis jedis = getSource();
try {
return jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeSource(jedis);
}
return null;
}
}
3.测试工具类
4. redis服务的feign模块编写
课程模块依赖feign模块,其中课程模块负责开启feign,feign模块负责导包和写接口(课程模块不用导了因为依赖)
1.导包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.编写feign接口
@FeignClient("redis-server")
public interface RedisFeignClient {
@PostMapping("/redis/set")
AjaxResult set(@RequestParam("key") String key, @RequestParam("value") String value);
@PostMapping("/redis/get/{key}")
AjaxResult get(@PathVariable("key") String key);
}
5. 课程服务集成feign
1.导包
课程服务虽然不需要写接口,但是启动类要开启feign啊,所以仍然要导包,导hrm-redis-feign就好了,里面集成了
<dependency>
<groupId>myllxy</groupId>
<artifactId>hrm-redis-feign</artifactId>
</dependency>
2.主启动类加注解
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("cn.myllxy.course.mapper")
@EnableFeignClients("cn.myllxy.feignclient")
public class CourseServerApplication2020 {
public static void main(String[] args) {
SpringApplication.run(CourseServerApplication2020.class);
}
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
6. 课程服务实现课程分类缓存
本质:查询的时候先从redis查,没有再查mysql,也没有就是真没有了,有的话返回数据并添加到redis缓存
1.代码逻辑
package cn.myllxy.course.service.impl;
import cn.myllxy.course.domain.CourseType;
import cn.myllxy.course.mapper.CourseTypeMapper;
import cn.myllxy.course.service.ICourseTypeService;
import cn.myllxy.feignclient.RedisFeignClient;
import cn.myllxy.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 课程目录 服务实现类
* </p>
*
* @author yaohuaipeng
* @since 2020-02-17
*/
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {
@Autowired
private RedisFeignClient redisFeignClient;
@Override
public List<CourseType> treeData() {
List<CourseType> courseTypes = null;
AjaxResult ajaxResult = redisFeignClient.get("course_type");
if (ajaxResult.isSuccess() && null != ajaxResult.getResultObj()) {
String jsonFromRedis = ajaxResult.getResultObj().toString();
courseTypes = JSON.parseArray(jsonFromRedis, CourseType.class);
} else {
courseTypes = baseMapper.selectList(null);
redisFeignClient.set("course_type", JSON.toJSONString(courseTypes));
}
ArrayList<CourseType> pcourseTypes = new ArrayList<>();
for (CourseType courseType : courseTypes) {
if (courseType.getPid() == 0) {
pcourseTypes.add(courseType);
}
if (courseType.getPid() != 0) {
CourseType tempCourseType = null;
for (CourseType type : courseTypes) {
if (type.getId().equals(courseType.getPid())) {
tempCourseType = type;
break;
}
}
if (tempCourseType != null) {
tempCourseType.getChildren().add(courseType);
}
}
}
return pcourseTypes;
}
}
2.redis抽取常量
抽取常量防止redis中key相同造成覆盖
3.redis缓存更新
- 当mysql的数据发生变化时,要同步更新到redis
- 什么时候mysql会发生变化,当执行insert、delete、add等方法时
- 所以我们在这几个方法中进行更新就好了
将以下代码放到crud方法中:
List<CourseType> courseTypes = baseMapper.selectList(null);
redisFeignClient.set("course_type", JSON.toJSONString(courseTypes));