自用
尚硅谷医通项目总结
5.10晚总结:
项目的模型搭建,各种数据库表的创建 项目的执行流程
自己的奶茶外卖订单项目的流程需要好好设计
springboot项目的基本项目结构
在项目中引入redis的方法:首先加入配置类 如RedisConfig 设置RedisTemplate规则和CacheManager缓存规则
/**
* @author lhr
* @Date:2022/5/6 15:31
* @Version 1.0
*/
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 设置RedisTemplate规则
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//序列号key value
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* 设置CacheManager缓存规则
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
在pom文件中导入依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-pool2artifactId>
<version>2.6.0version>
dependency>
在需要使用redis的module中编写配置文件
#配置redis链接
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0
#注册nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
由于在顶端设置了公共的redisTemplate,所以在项目中只需要在控制器中注入就可
/**
* @author lhr
* @Date:2022/5/5 10:44
* @Version 1.0
*/
@Api("数据字典接口")
@CrossOrigin
@RestController
@RequestMapping("/admin/cmn/dict")
public class CmnController {
@Autowired
private CmnService cmnService;
@Autowired
private RedisTemplate redisTemplate;
//redis测试连接
@GetMapping("/test")
public String testRedis(){
ArrayList arrayList = (ArrayList) redisTemplate.opsForValue().get("dict::com.lhr.yygh.cmn.service.impl.CmnServiceImplfindChildData1"
);
redisTemplate.opsForValue().set("k111","chileshi");
String s = (String) redisTemplate.opsForValue().get("k111");
return arrayList.toString();
}
//导入数据字典接口
@PostMapping("/importData")
public Result importData(MultipartFile file){
cmnService.importData(file);
return Result.ok();
}
或者直接调用mybatis-plus中的serviceImpl来进行调用
@Service
public class CmnServiceImpl extends ServiceImpl<CmnMapper, Dict> implements CmnService{
/**
* 根据上级id获取子节点数据列表
* @param id
*/
@Cacheable(value = "dict",keyGenerator = "keyGenerator")
@Override
public List<Dict> findChildData(long id) {
QueryWrapper<Dict> wrapper = new QueryWrapper<>();
wrapper.eq("parent_id",id);
List<Dict> dictList = baseMapper.selectList(wrapper);
//在通过向dictList集合中每个dict对象设置hasChildren
dictList.forEach(dict -> {
dict.setHasChildren(isChildren(dict.getId()));
});
/**
* 或者以循环的方式查询设置
* for (Dict dict:dictList) {
* Long dictId = dict.getId();
* boolean b = isChildren(dictId);
* dict.setHasChildren(b); }
*/
return dictList;
}
//使用流的形式对list进行分组 *** 作
Map<String, List<Department>> departMap =
departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
使用mongoTemplate来实现数据的分组、聚合、统计 *** 作(Mongodb)
//根据hoscode,depcode来查询排班信息
@Override
public Map<String, Object> getScheduleRule(long page, long limit, String hoscode, String depcode) {
//根据hoscode和depcode查询 按照工作日期workDate进行分组
Criteria c = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
//统计号源的数量
Aggregation aggregation = Aggregation.newAggregation(
//匹配条件
Aggregation.match(c),
//分组字段
Aggregation.group("workDate").first("workDate")
.as("workDate")
//统计号源
.count().as("docCount")
.sum("reservedNumber").as("reservedNumber")
.sum("availableNumber").as("availableNumber"),
//排序
Aggregation.sort(Sort.Direction.DESC,"wordDate"),
//分页
Aggregation.skip(limit*(page-1)),
Aggregation.limit(limit)
);
//其中三个参数的意义分别为aggregation,封装实体类的class和返回参数的class
AggregationResults<BookingScheduleRuleVo> aggregate =
mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
//返回封装类的list集合
List<BookingScheduleRuleVo> results = aggregate.getMappedResults();
return null;
}
使用MongoRepository来进行简单的查询 *** 作
先建立一个ScheduleRepository的接口继承MongoRepository@Repository
public interface ScheduleRepository extends MongoRepository<Schedule,Object> {
Schedule getScheduleByHoscodeAndHosScheduleId(String hoscode, String hosScheduleId);
Schedule findScheduleByHoscodeAndHosScheduleId(String hoscode, String hosScheduleId);
}//MongoRepository有固定的查询语法规定 自动生成语句
//使用MongoRepository来进行查询并分页
@Override
public Page<Department> findPageDepartment(DepartmentQueryVo vo, int page, int limit) {
//进行校验 通过展示不通过300
//将vo对象转换为department对象
Department department = new Department();
BeanUtils.copyProperties(vo,department);
department.setIsDeleted(0);
//创建page对象进行分页 用的方法是pageRequest
Pageable pageable = PageRequest.of(page,limit);
//创建匹配器和example对象
ExampleMatcher exampleMatcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase(true);
Example example = Example.of(department,exampleMatcher);
Page<Department> voList = departmentRepository.findAll(example, pageable);
return voList;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)