栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【无标题】个人总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【无标题】个人总结

学习总结5.10:

自用

尚硅谷医通项目总结


5.10晚总结:

项目的模型搭建,各种数据库表的创建 项目的执行流程
自己的奶茶外卖订单项目的流程需要好好设计
springboot项目的基本项目结构

common:

在项目中引入redis的方法:首先加入配置类 如RedisConfig 设置RedisTemplate规则和CacheManager缓存规则

@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();
            }
        };
    }

    
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate 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;
    }

    
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer 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文件中导入依赖:

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

        
        
            org.apache.commons
            commons-pool2
            2.6.0
        

在需要使用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,所以在项目中只需要在控制器中注入就可


@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 implements CmnService{
    

    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List findChildData(long id) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List dictList = baseMapper.selectList(wrapper);
        //在通过向dictList集合中每个dict对象设置hasChildren
        dictList.forEach(dict -> {
            dict.setHasChildren(isChildren(dict.getId()));
        });
        
        return dictList;
    }
 //使用流的形式对list进行分组操作
        Map> departMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
使用mongoTemplate来实现数据的分组、聚合、统计操作(Mongodb)
       //根据hoscode,depcode来查询排班信息
    @Override
    public Map 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 aggregate =
                mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //返回封装类的list集合
        List results = aggregate.getMappedResults();
        return null;
    }
使用MongoRepository来进行简单的查询操作 先建立一个ScheduleRepository的接口继承MongoRepository(实体类,返回参数class)
@Repository
public interface ScheduleRepository extends MongoRepository {
    Schedule getScheduleByHoscodeAndHosScheduleId(String hoscode, String hosScheduleId);
    Schedule findScheduleByHoscodeAndHosScheduleId(String hoscode, String hosScheduleId);
}//MongoRepository有固定的查询语法规定 自动生成语句
    //使用MongoRepository来进行查询并分页
    @Override
    public Page 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 voList = departmentRepository.findAll(example, pageable);
        return voList;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/873779.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号