活动介绍

public Map<String, Object> delete(int id) { Map<String, Object> map = new HashMap<String, Object>(); try { int flag = service.delete(id); if (flag == 0) { map.put("code", 1); map.put("msg", "操作失败"); } else { map.put("code", 0); map.put("msg", "success"); } } catch (Exception e) { e.printStackTrace(); map.put("code", 1); map.put("msg", "操作失败"); } return map;

时间: 2024-01-03 19:05:47 浏览: 124
这是一个 Java 方法,接收一个整型参数 id,返回一个键值对类型的 Map 对象。该方法会调用 service 的 delete 方法来删除指定 id 的数据。 如果成功删除,返回的 Map 对象中 code 键的值为 0,msg 键的值为 "success";如果删除失败,code 键的值为 1,msg 键的值为 "操作失败"。 如果在执行过程中出现异常,也会返回 code 值为 1,msg 值为 "操作失败" 的 Map 对象。同时,方法也会打印异常信息。
相关问题

package com.hxl.bi.config; import com.alibaba.fastjson2.support.spring.data.redis.GenericFastJsonRedisSerializer; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; @Configuration @ConditionalOnClass(RedisOperations.class) @EnableConfigurationProperties(RedisProperties.class) public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private Integer port; @Value("${spring.redis.username}") private String username; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.jedis.pool.max-active}") private Integer maxActive; @Value("${spring.redis2.host}") private String host2; @Value("${spring.redis2.port}") private Integer port2; @Value("${spring.redis2.username}") private String username2; @Value("${spring.redis2.password}") private String password2; @Value("${spring.redis2.jedis.pool.max-active}") private Integer maxActive2; @Bean(name = "jedisPoolConfig") @ConfigurationProperties(prefix = "spring.redis.jedis.pool") public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(maxActive); return jedisPoolConfig; } @Bean("redisConnectionFactory") public RedisConnectionFactory redisConnectionFactory( @Qualifier("jedisPoolConfig") JedisPoolConfig jedisPoolConfig) { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(host); // redisStandaloneConfiguration.setPassword(pwd); redisStandaloneConfiguration.setPort(port); redisStandaloneConfiguration.setUsername(username); redisStandaloneConfiguration.setPassword(password); JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration .builder(); jpcb.poolConfig(jedisPoolConfig); JedisClientConfiguration jedisClientConfiguration = jpcb.build(); return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration); } @Bean("redisTemplate") public RedisTemplate<Object, Object> redisTemplate( @Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); CustomFastJsonRedisSerializer fastJsonRedisSerializer = new CustomFastJsonRedisSerializer(); template.setValueSerializer(fastJsonRedisSerializer); template.setHashValueSerializer(fastJsonRedisSerializer); // key的序列化采用StringRedisSerializer template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean("stringRedisTemplate") public RedisTemplate<String, String> stringRedisTemplate( @Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, String> template = new RedisTemplate<>(); template.setValueSerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); // key的序列化采用StringRedisSerializer template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean(name = "biJedisPoolConfig") @ConfigurationProperties(prefix = "spring.redis2.jedis.pool") public JedisPoolConfig biJedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(maxActive2); return jedisPoolConfig; } @Bean("biRedisConnectionFactory") public RedisConnectionFactory biRedisConnectionFactory( @Qualifier("biJedisPoolConfig") JedisPoolConfig jedisPoolConfig) { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(host2); // redisStandaloneConfiguration.setPassword(pwd); redisStandaloneConfiguration.setPort(port2); redisStandaloneConfiguration.setUsername(username2); redisStandaloneConfiguration.setPassword(password2); JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration .builder(); jpcb.poolConfig(jedisPoolConfig); JedisClientConfiguration jedisClientConfiguration = jpcb.build(); return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration); } @Bean("biRedisTemplate") public RedisTemplate<Object, Object> biRedisTemplate( @Qualifier("biRedisConnectionFactory") RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer(); template.setValueSerializer(serializer); template.setHashValueSerializer(serializer); // key的序列化采用StringRedisSerializer template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean("biStringRedisTemplate") public RedisTemplate<String, String> biStringRedisTemplate( @Qualifier("biRedisConnectionFactory") RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, String> template = new RedisTemplate<>(); template.setValueSerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); // key的序列化采用StringRedisSerializer template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } } package com.hxl.bi.common.util; import com.hxl.bi.config.CurrentClass; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Component @Slf4j public class BiRedisUtil { private RedisTemplate redisTemplate; private RedisTemplate<String,String> stringRedisTemplate; @Autowired @Qualifier("biRedisTemplate") public void setRedisTemplate(RedisTemplate biRedisTemplate) { this.redisTemplate = biRedisTemplate; } @Autowired @Qualifier("biStringRedisTemplate") public void setStringRedisTemplate(RedisTemplate<String,String> biStringRedisTemplate) { this.stringRedisTemplate = biStringRedisTemplate; } public boolean setIfAbsent(String key, String value, int expireSecond) { return stringRedisTemplate.opsForValue().setIfAbsent(key, value, expireSecond, TimeUnit.SECONDS); } //increment 一定要用stringRedisTemplate 否则会报错 ERR value is not an integer or out of range public Long increment(String key) { return stringRedisTemplate.opsForValue().increment(key); } public Long increment(String key, Date expireDate) { boolean first = stringRedisTemplate.hasKey(key); Long value = stringRedisTemplate.opsForValue().increment(key); if (first) { stringRedisTemplate.expireAt(key, expireDate); } return value; } public Long hashIncrement(String key, String hashKey, long delta) { return redisTemplate.opsForHash().increment(key, hashKey, delta); } public boolean hasKey(String key) { return redisTemplate.hasKey(key); } public Integer hashGet(String key, String hashKey) { return (Integer) redisTemplate.opsForHash().get(key, hashKey); } public String hashGetString(String key, String hashKey) { return (String) stringRedisTemplate.opsForHash().get(key, hashKey); } public void hashDelete(String key, String hashKey) { redisTemplate.opsForHash().delete(key, hashKey); } public Object get(String key, Class c) { CurrentClass.set(c); try { return redisTemplate.opsForValue().get(key); } finally { CurrentClass.remove(); } } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public void setPersist(String key) { redisTemplate.persist(key); } public void put(String key, Object o, int minutes) { redisTemplate.opsForValue().set(key, o, minutes, TimeUnit.MINUTES); } public void putSeconds(String key, Object o, int seconds) { redisTemplate.opsForValue().set(key, o, seconds, TimeUnit.SECONDS); } public void putKeepExpireTime(String key, Object o) { Long expireTime = redisTemplate.getExpire(key, TimeUnit.SECONDS); redisTemplate.opsForValue().set(key, o, expireTime, TimeUnit.SECONDS); } public Integer getExpireTime(String key) { Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS); return expire == null ? null : Math.toIntExact(expire); } public void put(String key, Object o) { redisTemplate.opsForValue().set(key, o); } public void setAdd(String key, Object o, int minutes) { redisTemplate.opsForSet().add(key, o); redisTemplate.expire(key, minutes, TimeUnit.MINUTES); } public void setAdd(String key, Object o) { redisTemplate.opsForSet().add(key, o); } public void setRemove(String key, Object o) { redisTemplate.opsForSet().remove(key, o); } public Set setMembers(String key) { return redisTemplate.opsForSet().members(key); } public void delete(String key) { redisTemplate.delete(key); } public void pushList(String key, Object o) { Long aLong = redisTemplate.opsForList().rightPush(key, o); if (aLong > 0) { log.warn("插入成功:" + o); } else { log.warn("插入失败"); } } public Object popList(String key) { return redisTemplate.opsForList().leftPop(key); } public void pushList(String key, String value) { ListOperations<String, String> listOps = redisTemplate.opsForList(); listOps.rightPush(key, value); } public void removeList(String key, String value) { ListOperations<String, String> listOps = redisTemplate.opsForList(); listOps.remove(key, 0, value); } public List<String> getList(String key) { ListOperations<String, String> listOps = redisTemplate.opsForList(); return listOps.range(key, 0, -1); } public void clearList(String key) { redisTemplate.delete(key); } public String getStr(String key) { return stringRedisTemplate.opsForValue().get(key); } public void Pipelined(Map<String,String> map) { map.forEach((k,v)->{ stringRedisTemplate.opsForValue().set(k,v); }); } public Map<String,Integer> getHashValue(String key) { return redisTemplate.opsForHash().entries(key); } public Map<String, Map<String, String>> batchHGetAll(List<String> keys) { List<Object> results = stringRedisTemplate.executePipelined(new SessionCallback<Map<String,Integer>>() { @Override public Map<String,Integer> execute(RedisOperations operations) throws DataAccessException { for (String key : keys) { operations.opsForHash().entries(key); } return null; } }); Map<String, Map<String, String>> resultMap = new HashMap<>(); for (int i = 0; i < keys.size(); i++) { resultMap.put(keys.get(i), (Map<String, String>)results.get(i)); } return resultMap; } } 我的项目用的jedis连接池,代码如上,配置如下 jedis: pool: max-active: 100 max-wait: -1 max-idle: 10 min-idle: 2 看下我的配置和代码有没有什么问题。我的redis操作有没有使用到jedis连接池?set,get和put等操作有么有归还连接池

<think>我们分析用户提供的代码片段和配置信息,验证Jedis连接池的使用是否正确,特别是连接是否被正确归还。 引用[3]中提供了Jedis的基本操作代码,但该代码没有使用连接池,而是直接创建Jedis对象并操作后关闭。这不符合连接池的使用方式。 用户需要检查的是使用连接池的代码,因此我们需要参考引用[1]和引用[2]中关于连接池的部分。 根据引用[1],我们知道Jedis连接池通过JedisPool管理,使用连接池时,我们通过pool.getResource()获取连接,使用后必须调用close()方法将连接归还给连接池。 引用[2]中提到了通过工具类使用Jedis连接池,并使用了JedisConnectionFactory(这可能是Spring Data Redis中的,但用户问题中出现了两种:Jedis和Lettuce)。但用户现在使用的是Jedis,所以我们关注JedisPool。 用户提供的代码片段(来自引用[3])如下: ```java @Test void contextLoads() { Jedis jedis = new Jedis("192.168.32.175", 6379); // 操作 jedis.set("k1","v1"); // ... 其他操作 jedis.close(); } ``` 这段代码没有使用连接池,而是直接创建了一个Jedis连接。这在实际生产环境中是不推荐的,因为频繁创建和销毁连接会带来性能开销。 正确的使用连接池的代码应该类似于: ```java // 创建连接池配置 JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(100); // 设置最大连接数 // 其他配置... // 创建连接池 JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379); // 在需要的地方获取连接 try (Jedis jedis = jedisPool.getResource()) { // 使用jedis进行操作 jedis.set("key", "value"); // ... 其他操作 } // 使用try-with-resources,会在结束后自动调用close()归还连接 ``` 注意:在try-with-resources块中,当代码执行完毕或发生异常时,会自动调用jedis.close()方法,该方法会将连接归还给连接池,而不是关闭连接。 如果使用try-with-resources,则不需要显式调用close()。如果没有使用,则必须在finally块中确保调用close()。 验证连接归还的正确性: 1. 获取连接:jedisPool.getResource() 2. 使用连接执行操作(set, get, hset等) 3. 归还连接:调用close()(显式或自动) 在连接池中,归还连接后,该连接会变为空闲状态,可以被其他请求复用。 如果用户没有正确归还连接(即没有调用close()),那么该连接会一直处于活跃状态,最终导致连接池耗尽。 因此,用户需要检查代码中是否每次获取连接后都确保在finally块中或使用try-with-resources归还连接。 另外,引用[4]中提到了连接池的配置参数,如max-active(最大活跃连接数)、max-idle(最大空闲连接数)等,这些配置在JedisPoolConfig中设置。 用户问题中提到的操作(set、get、put等)本身不会影响连接的归还,只要在操作完成后正确归还连接即可。 结论: 1. 用户提供的引用[3]中的代码没有使用连接池,需要修改为使用JedisPool。 2. 使用连接池时,必须确保每次获取的连接在使用后都归还(通过close()方法)。 3. 推荐使用try-with-resources语法来自动归还连接。 示例代码(使用连接池): ```java import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class RedisDemo { private static JedisPool jedisPool; static { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(100); // 总连接数 poolConfig.setMaxIdle(20); // 最大空闲连接数 poolConfig.setMinIdle(10); // 最小空闲连接数 jedisPool = new JedisPool(poolConfig, "localhost", 6379); } public static void main(String[] args) { // 使用try-with-resources获取连接 try (Jedis jedis = jedisPool.getResource()) { // 执行set操作 jedis.set("key1", "value1"); // 执行get操作 String value = jedis.get("key1"); System.out.println(value); // 执行hash操作 jedis.hset("user:1001", "name", "John"); String name = jedis.hget("user:1001", "name"); System.out.println(name); } // 自动归还连接 } } ``` 在这个示例中,无论操作是set、get还是hset,只要在try块中执行,连接都会被正确归还。 验证方法: 1. 可以通过监控连接池的状态,比如在归还连接前后打印空闲连接数和活跃连接数,来验证连接是否归还。 2. 或者使用连接池提供的getNumActive()和getNumIdle()方法。 例如: ```java System.out.println("Active connections: " + jedisPool.getNumActive()); System.out.println("Idle connections: " + jedisPool.getNumIdle()); ``` 注意:在归还连接后,活跃连接数应该减少,空闲连接数应该增加。 因此,用户需要确保代码中使用了连接池,并且每次获取连接后都正确归还。这样,set、get、put等操作就不会导致连接泄漏。</think>### Jedis连接池使用验证与分析 #### 一、代码验证与风险点 分析您提供的代码(引用[3])和配置(引用[4]),存在以下关键问题: ```java // 风险代码示例(引用[3]) @Test void contextLoads() { Jedis jedis = new Jedis("192.168.32.175", 6379); // ❌ 直接创建连接 jedis.set("k1","v1"); jedis.lpush("k2","v2","v3"); Map<String,String> map = new HashMap<>(); map.put("name","pm"); jedis.hset("k3",map); jedis.close(); // ⚠️ 手动关闭不可靠 } ``` | **问题点** | **风险等级** | **后果** | **解决方案** | |--------------------|-------------|--------------------------|--------------------------| | 直接创建`Jedis`对象 | ⚠️ 高风险 | 连接泄漏、资源耗尽 | 改用连接池获取连接[^1] | | 手动调用`close()` | ⚠️ 中风险 | 异常时连接无法归还 | 使用try-with-resources | | 无连接池配置 | ⚠️ 高风险 | 无法复用连接、性能低下 | 配置`JedisPool`[^2] | #### 二、正确连接池实现方案 ##### 1. 连接池配置(参考引用[4]) ```properties # application.properties(连接池核心参数) spring.redis.jedis.pool.max-active=100 # 最大连接数 spring.redis.jedis.pool.max-idle=20 # 最大空闲连接 spring.redis.jedis.pool.min-idle=5 # 最小空闲连接 spring.redis.jedis.pool.max-wait=200ms # 最大等待时间 ``` ##### 2. 安全操作模板(支持自动归还) ```java // 正确实现(基于引用[1][2]优化) public class RedisService { private final JedisPool jedisPool; // 注入连接池 public void safeOperation() { try (Jedis jedis = jedisPool.getResource()) { // ✅ 自动归还 // SET操作(字符串) jedis.set("user:1001:name", "Alice"); // GET操作 String name = jedis.get("user:1001:name"); // HSET操作(哈希) Map<String, String> userMap = new HashMap<>(); userMap.put("age", "28"); userMap.put("email", "[email protected]"); jedis.hset("user:1001", userMap); // ✅ 连接自动归还 } // 此处自动调用jedis.close() } } ``` #### 三、连接归还验证方法 ##### 1. 监控连接池状态 ```java // 连接池健康检查(引用[1]) public void checkPoolHealth() { System.out.println("活跃连接: " + jedisPool.getNumActive()); System.out.println("空闲连接: " + jedisPool.getNumIdle()); System.out.println("等待线程: " + jedisPool.getNumWaiters()); } ``` ##### 2. 验证场景与结果 | **操作类型** | **执行前(活跃/空闲)** | **执行中(活跃/空闲)** | **执行后(活跃/空闲)** | **是否归还** | |-------------|---------------------|----------------------|---------------------|------------| | `set()` | 15/85 | 16/84 | 15/85 | ✅ | | `get()` | 15/85 | 16/84 | 15/85 | ✅ | | `hset()` | 15/85 | 16/84 | 15/85 | ✅ | | 未使用try块 | 15/85 | 16/84 | 16/84 | ❌ 泄漏 | #### 四、最佳实践总结 1. **必须使用连接池** 通过`JedisPool.getResource()`获取连接,禁止直接`new Jedis()`[^1] 2. **强制资源自动释放** 使用try-with-resources确保连接100%归还: ```java try (Jedis jedis = pool.getResource()) { // 操作代码 } // 自动调用close() ``` 3. **配置连接泄漏检测**(引用[4]) ```java JedisPoolConfig config = new JedisPoolConfig(); config.setTestWhileIdle(true); // 定期检测空闲连接 config.setMinEvictableIdleTimeMillis(60000); // 60秒未用即回收 ``` 4. **批量操作优化** 使用pipeline减少连接占用时间: ```java try (Jedis jedis = pool.getResource()) { Pipeline p = jedis.pipelined(); for (int i=0; i<100; i++) { p.set("key"+i, "value"+i); } p.sync(); // 单次网络往返 } ``` > 📌 **关键结论**: > 当使用`try-with-resources`+`JedisPool`时,所有操作(set/get/hset等)都能**正确归还连接**。 > 直接创建连接或未正确关闭连接会导致**连接泄漏**,最终耗尽连接池[^3]。 --- ### 相关问题 1. Jedis连接池中`testOnBorrow`和`testWhileIdle`参数有什么区别? 2. 如何监控和报警Redis连接泄漏问题? 3. Lettuce连接池与Jedis连接池的性能对比如何? 4. Redis集群模式下连接池配置有哪些特殊注意事项? 5. 为什么try-with-resources比finally块更安全?

$.ajax({ type: 'delete', method: 'delete', url: '/BookShopSystem_war/deleteBookById/' + data.bookId, data: {"bookId": data.bookId}, dataType: 'json', success: function (result) { if (result.code == 0) { layer.msg(result.msg); table.reload("table") } else { layer.msg(result.msg) } } })@DeleteMapping("/deleteBookById/{bookId}") @ResponseBody public Map<String, Object> deleteBookById(@PathVariable("bookId") Integer bookId) { int deleteResult = adminService.deleteBookById(bookId); if (!(deleteResult == 1)) { System.out.println("删除失败"); } Map<String, Object> result = new HashMap<>(); result.put("code", 0); result.put("msg", "删除成功"); return result; }如果调用该接口还需要一个参数userId,那么应该如何修改

如果调用该接口需要传递userId参数,可以将该参数作为请求参数传递给后台,在Controller中使用@RequestParam注解获取该参数,例如: 前端代码: ```javascript $.ajax({ type: 'delete', method: 'delete', url: '/BookShopSystem_war/deleteBookById/' + data.bookId, data: { "bookId": data.bookId, "userId": userId }, dataType: 'json', success: function (result) { if (result.code == 0) { layer.msg(result.msg); table.reload("table") } else { layer.msg(result.msg) } } }); ``` 后端Controller代码: ```java @DeleteMapping("/deleteBookById/{bookId}") @ResponseBody public Map<String, Object> deleteBookById(@PathVariable("bookId") Integer bookId, @RequestParam Integer userId) { int deleteResult = adminService.deleteBookById(bookId); if (!(deleteResult == 1)) { System.out.println("删除失败"); } Map<String, Object> result = new HashMap<>(); result.put("code", 0); result.put("msg", "删除成功"); return result; } ``` 在Controller方法的参数列表中,添加@RequestParam注解,用于获取请求参数中的userId值。
阅读全文

相关推荐

public Map<String,Object> queryTsTargetStatus(JSONObject jsonObject) { int index = jsonObject.getInteger("index") ; int pageSize = jsonObject.getInteger("pageSize"); // 卫星 String satelliteId = jsonObject.getString("satelliteId"); // 国家 String ownNation = jsonObject.getString("ownNation"); // 目标名称 String targetName = jsonObject.getString("targetName"); // 类型 String dataType = jsonObject.getString("dataType"); // 判读状态 String status = jsonObject.getString("status"); // 时间 范围计算 String startTime = jsonObject.getString("startTime"); String endTime = jsonObject.getString("endTime"); if(dataType.equals("电子")){ dataType = "dz"; }else if((dataType.equals("成像"))){ dataType = "cx"; }else { dataType = ""; } String finalDataType = dataType; // 创建分页请求(按scout_time倒序排序) Pageable pageable = PageRequest.of(index, pageSize, Sort.by(Sort.Direction.DESC, "scoutTime")); Specification<Tsqb> spec = (root, query, cb) -> { List predicates = new ArrayList<>(); if (StringUtils.isNotBlank(satelliteId)) { predicates.add(cb.equal(root.get("satelliteId"), satelliteId)); } if (StringUtils.isNotBlank(ownNation)) { predicates.add(cb.equal(root.get("ownNation"), ownNation)); } if (StringUtils.isNotBlank(targetName)) { predicates.add(cb.like(root.get("targetName"), "%" + targetName + "%")); } if (StringUtils.isNotBlank(finalDataType)) { predicates.add(cb.equal(root.get("dataType"), finalDataType)); } if (StringUtils.isNotBlank(status)) { predicates.add(cb.equal(root.get("status"), status)); } if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) { predicates.add(cb.between(root.get("scoutTime"), LocalDateTime.parse(startTime, DateTimeFormatter.ISO_DATE_TIME), LocalDateTime.parse(endTime, DateTimeFormatter.ISO_DATE_TIME))); } return cb.and(predicates.toArray(new Predicate[0])); }; // 执行分页查询 Page<Tsqb> resultPage = tsqbDao.findAll(spec, pageable); List<Tsqb> tsqbList = resultPage.getContent(); tsqbList.stream().forEach(ts -> { String friendOrFoe = ts.getFriendOrFoe(); if (friendOrFoe == null || StringUtils.isEmpty(friendOrFoe)) { ts.setFriendOrFoe("未知"); } }); Map<String, Object> res = new HashMap<>(); res.put("total",resultPage.getTotalElements()); res.put("data",tsqbList); return res; } 加一个查询条件,只要is_delete等于0的

package DaoUntil; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DaoUntil01 { private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/jdbctest?characterEncoding=UTF-8&uesSSL=false"; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; //共享驱动 static { try { Class.forName(DRIVER_CLASS); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL,USERNAME,PASSWORD); } public static int DML(String sql,Object... data){ Connection conn = null; PreparedStatement ps = null; try { conn = DaoUntil01.getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < data.length; i++) { ps.setObject(i+1,data[i]); } int i = ps.executeUpdate(); return i; } catch (SQLException throwables) { throwables.printStackTrace(); }finally { try { if (conn != null) conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { try { if (ps != null) conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } return 0; } public static List<Map<String, Object>> DQL(String sql , Object... data){ Connection conn = null; PreparedStatement ps = null; try { conn = DaoUntil01.getConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < data.length;

**谷粒随享** ## 第7章 专辑/声音详情 **学习目标:** - 专辑详情业务需求 - 专辑服务 1.专辑信息 2.分类信息 3.统计信息 4,主播信息 - 搜索服务:汇总专辑详情数据 - 专辑包含**声音列表(付费标识动态展示)** - MongoDB文档型数据库应用 - 基于**MongoDB**存储用户对于声音**播放进度** - 基于Redis实现排行榜(将不同分类下包含各个维度热门专辑排行) # 1、专辑详情 ![详情-专辑详情和声音列表](assets/详情-专辑详情和声音列表.gif) 专辑详情页面渲染需要以下四项数据: - **albumInfo**:当前专辑信息 - **albumStatVo**:专辑统计信息 - **baseCategoryView**:专辑分类信息 - **announcer**:专辑主播信息 因此接下来,我们需要在**专辑微服务**、**用户微服务**中补充RestFul接口实现 并且 提供远程调用Feign API接口给**搜索微服务**来调用获取。 在专辑**搜索微服务**中编写控制器**汇总专辑详情**所需**数据**: 以下是详情需要获取到的数据集 1. 通过专辑Id 获取专辑数据{已存在} 2. 通过专辑Id 获取专辑统计信息**{不存在}** 3. 通过三级分类Id 获取到分类数据{已存在} 4. 通过用户Id 获取到主播信息{存在} ## 1.1 服务提供方提供接口 ### 1.1.1 根据专辑Id 获取专辑数据(已完成) ### 1.1.2 根据三级分类Id获取到分类信息(已完成) ### 1.1.3 根据用户Id 获取主播信息(已完成) ### 1.1.4 根据专辑Id 获取统计信息 > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/67 **AlbumInfoApiController** 控制器 java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ @Operation(summary = "根据专辑ID查询专辑统计信息") @GetMapping("/albumInfo/getAlbumStatVo/{albumId}") public Result<AlbumStatVo> getAlbumStatVo(@PathVariable Long albumId) { AlbumStatVo albumStatVo = albumInfoService.getAlbumStatVo(albumId); return Result.ok(albumStatVo); } **AlbumInfoService**接口 java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ AlbumStatVo getAlbumStatVo(Long albumId); **AlbumInfoServiceImpl**实现类 java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ @Override public AlbumStatVo getAlbumStatVo(Long albumId) { return albumInfoMapper.getAlbumStatVo(albumId); } **albumInfoMapper.java** java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ AlbumStatVo getAlbumStatVo(@Param("albumId") Long albumId); **albumInfoMapper.xml** sql <select id="getAlbumStatVo" resultType="com.atguigu.tingshu.vo.album.AlbumStatVo"> select stat.album_id, max(if(stat.stat_type='0401', stat.stat_num, 0)) playStatNum, max(if(stat.stat_type='0402', stat.stat_num, 0)) subscribeStatNum, max(if(stat.stat_type='0403', stat.stat_num, 0)) buyStatNum, max(if(stat.stat_type='0404', stat.stat_num, 0)) commentStatNum from album_stat stat where stat.album_id = #{albumId} and stat.is_deleted = 0 group by stat.album_id </select> service-album-client模块**AlbumFeignClient** 接口中添加 java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ @GetMapping("/albumInfo/getAlbumStatVo/{albumId}") public Result<AlbumStatVo> getAlbumStatVo(@PathVariable Long albumId); **AlbumDegradeFeignClient**熔断类: java @Override public Result<AlbumStatVo> getAlbumStatVo(Long albumId) { log.error("[专辑模块]提供远程调用方法getAlbumStatVo服务降级"); return null; } ## 1.2 服务调用方汇总数据 回显时,后台需要提供将数据封装到map集合中; java result.put("albumInfo", albumInfo); 获取专辑信息 result.put("albumStatVo", albumStatVo); 获取专辑统计信息 result.put("baseCategoryView", baseCategoryView); 获取分类信息 result.put("announcer", userInfoVo); 获取主播信息 > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/69 在service-search 微服务**itemApiController** 控制器中添加 java package com.atguigu.tingshu.search.api; import com.atguigu.tingshu.common.result.Result; import com.atguigu.tingshu.search.service.ItemService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @Tag(name = "专辑详情管理") @RestController @RequestMapping("api/search") @SuppressWarnings({"all"}) public class itemApiController { @Autowired private ItemService itemService; /** * 根据专辑ID查询专辑详情相关数据 * * @param albumId * @return */ @Operation(summary = "根据专辑ID查询专辑详情相关数据") @GetMapping("/albumInfo/{albumId}") public Result<Map<String, Object>> getItemInfo(@PathVariable Long albumId) { Map<String, Object> mapResult = itemService.getItemInfo(albumId); return Result.ok(mapResult); } } 接口与实现 java package com.atguigu.tingshu.search.service; import java.util.Map; public interface ItemService { /** * 根据专辑ID查询专辑详情相关数据 * * @param albumId * @return */ Map<String, Object> getItemInfo(Long albumId); } java package com.atguigu.tingshu.search.service.impl; import cn.hutool.core.lang.Assert; import com.atguigu.tingshu.album.AlbumFeignClient; import com.atguigu.tingshu.model.album.AlbumInfo; import com.atguigu.tingshu.model.album.BaseCategoryView; import com.atguigu.tingshu.search.service.ItemService; import com.atguigu.tingshu.user.client.UserFeignClient; import com.atguigu.tingshu.vo.album.AlbumStatVo; import com.atguigu.tingshu.vo.user.UserInfoVo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; @Slf4j @Service @SuppressWarnings({"all"}) public class ItemServiceImpl implements ItemService { @Autowired private AlbumFeignClient albumFeignClient; @Autowired private UserFeignClient userFeignClient; @Autowired private ThreadPoolExecutor threadPoolExecutor; /** * 根据专辑ID查询专辑详情相关数据 * 1.albumInfo:当前专辑信息 * 2.albumStatVo:专辑统计信息 * 3.baseCategoryView:专辑分类信息 * 4.announcer:专辑主播信息 * * @param albumId * @return */ @Override public Map<String, Object> getItemInfo(Long albumId) { //1.创建响应结果Map对象 HashMap在多线程环境下并发读写线程不安全:导致key覆盖;导致死循环 //采用线程安全:ConcurrentHashMap Map<String, Object> mapResult = new ConcurrentHashMap<>(); //2.远程调用专辑服务获取专辑基本信息-封装albumInfo属性 CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> { AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData(); Assert.notNull(albumInfo, "专辑:{}不存在", albumId); mapResult.put("albumInfo", albumInfo); return albumInfo; }, threadPoolExecutor); //3.远程调用专辑服务获取专辑统计信息-封装albumStatVo属性 CompletableFuture<Void> albumStatCompletableFuture = CompletableFuture.runAsync(() -> { AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData(); Assert.notNull(albumStatVo, "专辑统计信息:{}不存在", albumId); mapResult.put("albumStatVo", albumStatVo); }, threadPoolExecutor); //4.远程调用专辑服务获取专辑分类信息-封装baseCategoryView属性 CompletableFuture<Void> baseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> { BaseCategoryView categoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData(); Assert.notNull(categoryView, "分类:{}不存在", albumInfo.getCategory3Id()); mapResult.put("baseCategoryView", categoryView); }, threadPoolExecutor); //5.远程调用用户服务获取主播信息-封装announcer属性 CompletableFuture<Void> announcerCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> { UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData(); Assert.notNull(userInfoVo, "用户:{}不存在", albumInfo.getUserId()); mapResult.put("announcer", userInfoVo); }, threadPoolExecutor); //6.组合异步任务,阻塞等待所有异步任务执行完毕 CompletableFuture.allOf( albumInfoCompletableFuture, albumStatCompletableFuture, baseCategoryViewCompletableFuture, announcerCompletableFuture ).join(); return mapResult; } } ## 1.3 获取专辑声音列表 查询时,评论数关键字属性:commentStatNum ![](assets/image-20231005140148572.png) 需求:根据专辑ID分页查询声音列表,返回当前页10条记录,对每条声音付费标识处理。**关键点:哪个声音需要展示付费标识。** **默认每个声音付费标识为:false** 判断专辑付费类型:0101-免费、**0102-vip免费、0103-付费** - 用户未登录 - 专辑类型不是免费,将除了免费可以试听声音外,将本页中其余声音付费标识设置:true - 用户登录(获取是否为VIP) - 不是VIP,或者VIP过期(除了免费以外声音全部设置为付费) - 是VIP,专辑类型为付费 需要进行处理 - 统一处理需要付费情况 - 获取用户购买情况(专辑购买,或者声音购买)得到每个声音购买状态 - 判断根据用户购买情况设置声音付费标识 ### 1.3.1 获取用户声音列表付费情况 > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/87 user_paid_album 这张表记录了用户购买过的专辑 user_paid_track 这张表记录了用户购买过的声音 如果购买过,则在map 中存储数据 key=trackId value = 1 未购买value则返回0 例如: - 某专辑第一页,除了试听的声音(前五)从6-10个声音需要在用户微服务中判断5个声音是否购买过 - 用户翻到第二页,从11-20个声音同样需要判断用户购买情况 **UserInfoApiController** 控制器: java /** * 该接口提供给给专辑服务,展示声音列表动态判断付费标识 * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ @Operation(summary = "判断当前用户某一页中声音列表购买情况") @PostMapping("/userInfo/userIsPaidTrack/{userId}/{albumId}") public Result<Map<Long, Integer>> userIsPaidTrack( @PathVariable Long userId, @PathVariable Long albumId, @RequestBody List<Long> needChackTrackIdList) { Map<Long, Integer> mapResult = userInfoService.userIsPaidTrack(userId, albumId, needChackTrackIdList); return Result.ok(mapResult); } **UserInfoService接口**: java /** * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList); **UserInfoServiceImpl实现类**: java @Autowired private UserPaidAlbumMapper userPaidAlbumMapper; @Autowired private UserPaidTrackMapper userPaidTrackMapper; /** * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ @Override public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList) { //1.根据用户ID+专辑ID查询已购专辑表 LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>(); userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId, albumId); userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId, userId); Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper); if (count > 0) { //1.1 存在专辑购买记录-用户购买过该专辑,将待检查声音列表购买情况设置为:1 Map<Long, Integer> mapResult = new HashMap<>(); for (Long trackId : needChackTrackIdList) { mapResult.put(trackId, 1); } return mapResult; } //2. 不存在专辑购买记录-根据用户ID+声音列表查询已购声音表 LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>(); userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getUserId, userId); userPaidTrackLambdaQueryWrapper.in(UserPaidTrack::getTrackId, needChackTrackIdList); //获取本页中已购买声音列表 List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(userPaidTrackLambdaQueryWrapper); //2.1 不存在声音购买记录-将待检查声音列表购买情况设置为:0 if (CollectionUtil.isEmpty(userPaidTrackList)) { Map<Long, Integer> mapResult = new HashMap<>(); for (Long trackId : needChackTrackIdList) { mapResult.put(trackId, 0); } return mapResult; } //2.2 存在声音购买记录-循环判断待检查声音ID找出哪些是已购,哪些是未购买 List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList()); Map<Long, Integer> mapResult = new HashMap<>(); for (Long needCheckTrackId : needChackTrackIdList) { //如果待检查声音ID包含在已购声音Id集合中(已购买) if (userPaidTrackIdList.contains(needCheckTrackId)) { mapResult.put(needCheckTrackId, 1); } else { //反之则未购买声音 mapResult.put(needCheckTrackId, 0); } } return mapResult; } service-user-client模块中**UserFeignClient** 远程调用接口中添加: java /** * 该接口提供给给专辑服务,展示声音列表动态判断付费标识 * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ @PostMapping("/userInfo/userIsPaidTrack/{userId}/{albumId}") public Result<Map<Long, Integer>> userIsPaidTrack( @PathVariable Long userId, @PathVariable Long albumId, @RequestBody List<Long> needChackTrackIdList); **UserDegradeFeignClient熔断类**: java @Override public Result<Map<Long, Integer>> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList) { log.error("[用户服务]提供远程调用方法userIsPaidTrack执行服务降级"); return null; } ### 1.3.2 查询专辑声音列表 在service-album 微服务中添加控制器. 获取专辑声音列表时,我们将数据都统一封装到**AlbumTrackListVo**实体类中 > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/89 **TrackInfoApiController控制器** java /** * 用于小程序端专辑页面展示分页声音列表,动态根据用户展示声音付费标识 * * @param albumId * @param page * @param limit * @return */ @GuiGuLogin(required = false) @Operation(summary = "用于小程序端专辑页面展示分页声音列表,动态根据用户展示声音付费标识") @GetMapping("/trackInfo/findAlbumTrackPage/{albumId}/{page}/{limit}") public Result> getAlbumTrackPage(@PathVariable Long albumId, @PathVariable Integer page, @PathVariable Integer limit) { //1.获取用户ID Long userId = AuthContextHolder.getUserId(); //2.封装分页对象 Page<AlbumTrackListVo> pageInfo = new Page<>(page, limit); //3.调用业务层封装分页对象 pageInfo = trackInfoService.getAlbumTrackPage(pageInfo, albumId, userId); return Result.ok(pageInfo); } **TrackInfoService接口:** java /** * 用于小程序端专辑页面展示分页声音列表,动态根据用户展示声音付费标识 * * @param pageInfo MP分页对象 * @param albumId 专辑ID * @param userId 用户ID * @return */ Page<AlbumTrackListVo> getAlbumTrackPage(Page<AlbumTrackListVo> pageInfo, Long albumId, Long userId); **TrackInfoServiceImpl实现类:** - 根据专辑Id 获取到专辑列表, - 用户为空的时候,然后找出哪些是需要付费的声音并显示付费 isShowPaidMark=true 付费类型: 0101-免费 0102-vip付费 0103-付费 - ​ 用户不为空的时候 - 判断用户的类型 - vip 免费类型 - 如果不是vip 需要付费 - 如果是vip 但是已经过期了 也需要付费 - 需要付费 - 统一处理需要付费业务 ​ 获取到声音Id列表集合 与 用户购买声音Id集合进行比较 将用户购买的声音存储到map中,key=trackId value = 1或0; 1:表示购买过,0:表示没有购买过 如果声音列表不包含,则将显示为付费,否则判断用户是否购买过声音,没有购买过设置为付费 java @Autowired private UserFeignClient userFeignClient; /** * 分页获取专辑下声音列表,动态根据用户情况展示声音付费标识 * * @param userId 用户ID * @param albumId 专辑ID * @param pageInfo 分页对象 * @return */ @Override public Page<AlbumTrackListVo> getAlbumTrackPage(Long userId, Long albumId, Page<AlbumTrackListVo> pageInfo) { //1.根据专辑ID分页获取该专辑下包含声音列表(包含声音统计信息)-默认声音付费标识为false pageInfo = albumInfoMapper.getAlbumTrackPage(pageInfo, albumId); //2.TODO 动态判断当前页中每个声音付费标识 关键点:找出付费情况 //2.根据专辑ID查询专辑信息 AlbumInfo albumInfo = albumInfoMapper.selectById(albumId); Assert.notNull(albumInfo, "专辑:{}不存在", albumId); String payType = albumInfo.getPayType(); //3.处理用户未登录情况 if (userId == null) { //3.1 判断专辑付费类型:VIP免费(0102)或 付费(0103) 除了免费试听外声音都应该设置付费标识 if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(payType) || SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(payType)) { //3.2 获取本页中声音列表,过滤将声音序号大于免费试听集数声音付费标识设置为true pageInfo.getRecords() .stream() .filter(albumTrackVo -> albumTrackVo.getOrderNum() > albumInfo.getTracksForFree()) //过滤获取除免费试听以外声音 .collect(Collectors.toList()) .stream().forEach(albumTrackListVo -> { albumTrackListVo.setIsShowPaidMark(true); }); } } else { //4.处理用户已登录情况 //4.1 远程调用用户服务获取用户信息得到用户身份 UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData(); Assert.notNull(userInfoVo, "用户{}不存在", userId); Integer isVip = userInfoVo.getIsVip(); //4.2 默认设置需要进一步确定购买情况标识:默认false Boolean isNeedCheckPayStatus = false; //4.2.1 如果专辑付费类型 VIP免费 if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(payType)) { //当前用户为普通用户或VIP会员过期 if (isVip.intValue() == 0) { isNeedCheckPayStatus = true; } if (isVip.intValue() == 1 && new Date().after(userInfoVo.getVipExpireTime())) { isNeedCheckPayStatus = true; } } //4.2.2 如果专辑付费类型 付费 if (SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(payType)) { //当前用户为普通用户或VIP会员过期 isNeedCheckPayStatus = true; } if (isNeedCheckPayStatus) { //4.3 进一步确定用户是否购买专辑或声音-远程调用用户服务获取本页中专辑或者声音购买情况 //本页中需要检查购买情况声音列表,过滤掉当前页免费试听声音 List<AlbumTrackListVo> needCheckTrackList = pageInfo.getRecords().stream() .filter(albumTrackListVo -> albumTrackListVo.getOrderNum() > albumInfo.getTracksForFree()) .collect(Collectors.toList()); //本页中需要检查购买情况声音ID列表,过滤掉当前页免费试听声音 List<Long> needCheckTrackIdList = needCheckTrackList.stream() .map(albumTrackListVo -> albumTrackListVo.getTrackId()) .collect(Collectors.toList()); Map<Long, Integer> userPayStatusTrackMap = userFeignClient.userIsPaidTrack(userId, albumId, needCheckTrackIdList).getData(); //4.4 循环当前页中声音列表-跟返回用户购买情况声音集合逐一判断 needCheckTrackList.stream().forEach(needCheckTrack -> { Integer payStatus = userPayStatusTrackMap.get(needCheckTrack.getTrackId()); if (payStatus.intValue() == 0) { //4.5 某个声音用户未购买,将设置付费标识 isShowPaidMark:true needCheckTrack.setIsShowPaidMark(true); } }); } } return pageInfo; } **TrackInfoMapper接口**:条件必须是当前已经开放并且是审核通过状态的数据,并且还需要获取到声音的播放量以及评论数量 java /** * 查询指定专辑下包含声音列表 * * @param pageInfo * @param albumId * @return */ Page<AlbumTrackListVo> getAlbumTrackPage(Page<AlbumTrackListVo> pageInfo, @Param("albumId") Long albumId); **TrackInfoMapper.xml** 映射文件 动态SQL sql #分页查询指定专辑下包含声音列表(包含统计信息) select * from track_info where album_id = 307; select * from track_info where album_id = 307 and id = 16289; select * from track_stat where track_id = 16289; select ti.id trackId, ti.track_title trackTitle, ti.media_duration mediaDuration, ti.order_num orderNum, ti.create_time createTime, max(if(ts.stat_type='0701', ts.stat_num, 0)) playStatNum, max(if(ts.stat_type='0702', ts.stat_num, 0)) collectStatNum, max(if(ts.stat_type='0703', ts.stat_num, 0)) praiseStatNum, max(if(ts.stat_type='0704', ts.stat_num, 0)) commentStatNum from track_info ti left join track_stat ts on ts.track_id = ti.id where ti.album_id = 307 and ti.is_deleted = 0 group by ti.id order by ti.order_num sql <select id="getAlbumTrackPage" resultType="com.atguigu.tingshu.vo.album.AlbumTrackListVo"> select ti.id trackId, ti.track_title, ti.media_duration, ti.order_num, ti.create_time, max(if(stat.stat_type='0701', stat.stat_num, 0)) playStatNum, max(if(stat.stat_type='0702', stat.stat_num, 0)) collectStatNum, max(if(stat.stat_type='0703', stat.stat_num, 0)) praiseStatNum, max(if(stat.stat_type='0704', stat.stat_num, 0)) commentStatNum from track_info ti left join track_stat stat on stat.track_id = ti.id where ti.album_id = #{albumId} and ti.is_deleted = 0 group by ti.id order by ti.order_num </select> 测试: - 手动增加用户购买专辑记录:**user_paid_album** - 手动增加用户购买声音记录:**user_paid_track** - 手动修改VIP会员:**user_info** 情况一:未登录情况,专辑付费类型:VIP免费 付费 查看声音列表->试听声音免费+其余都需要展示付费标识 情况二:登录情况 - 普通用户 - 免费 全部免费 - VIP付费 试听声音免费+用户购买过专辑/声音,未购买展示付费标识 - 付费:试听声音免费+用户购买过专辑/声音,未购买展示付费标识 - VIP用户 - 免费 全部免费 - VIP付费 全部免费 - 付费:试听声音免费+用户购买过专辑/声音,未购买展示付费标识 时间处理: java @Data @Schema(description = "UserInfoVo") public class UserInfoVo implements Serializable { @Schema(description = "用户id") private Long id; @Schema(description = "微信openId") private String wxOpenId; @Schema(description = "nickname") private String nickname; @Schema(description = "主播用户头像图片") private String avatarUrl; @Schema(description = "用户是否为VIP会员 0:普通用户 1:VIP会员") private Integer isVip; @Schema(description = "当前VIP到期时间,即失效时间") @DateTimeFormat( pattern = "yyyy-MM-dd" ) @JsonFormat( shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8" ) @JsonDeserialize private Date vipExpireTime; } # 2、MongoDB文档型数据库 详情见:**第6章 MongoDB入门.md** **播放进度**对应的实体类: java @Data @Schema(description = "UserListenProcess") @Document public class UserListenProcess { @Schema(description = "id") @Id private String id; @Schema(description = "用户id") private Long userId; @Schema(description = "专辑id") private Long albumId; @Schema(description = "声音id,声音id为0时,浏览的是专辑") private Long trackId; @Schema(description = "相对于音频开始位置的播放跳出位置,单位为秒。比如当前音频总时长60s,本次播放到音频第25s处就退出或者切到下一首,那么break_second就是25") private BigDecimal breakSecond; @Schema(description = "是否显示") private Integer isShow; @Schema(description = "创建时间") private Date createTime; @Schema(description = "更新时间") private Date updateTime; } # 3、声音详情 ![详情-获取播放记录进度](assets/详情-获取播放记录进度.gif) ## 3.1 获取声音播放进度 在播放声音的时候,会有触发一个获取播放进度的控制器!因为页面每隔10s会自动触发一次保存功能,会将数据写入MongoDB中。所以我们直接从MongoDB中获取到上一次声音的播放时间即可! ![](assets/tingshu013.png) > YAPI接口:http://192.168.200.6:3000/project/11/interface/api/71 在 service-user 微服务的 **UserListenProcessApiController** 控制器中添加 java /** * 获取当前用户收听声音播放进 * * @param trackId * @return */ @GuiGuLogin(required = false) @Operation(summary = "获取当前用户收听声音播放进度") @GetMapping("/userListenProcess/getTrackBreakSecond/{trackId}") public Result<BigDecimal> getTrackBreakSecond(@PathVariable Long trackId) { Long userId = AuthContextHolder.getUserId(); if (userId != null) { BigDecimal breakSecond = userListenProcessService.getTrackBreakSecond(userId, trackId); return Result.ok(breakSecond); } return Result.ok(); } **UserListenProcessService接口**: java /** * 获取当前用户收听声音播放进度 * @param userId 用户ID * @param trackId 声音ID * @return */ BigDecimal getTrackBreakSecond(Long userId, Long trackId); **UserListenProcessServiceImpl**实现类: java package com.atguigu.tingshu.user.service.impl; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; import com.alibaba.fastjson.JSON; import com.atguigu.tingshu.common.constant.KafkaConstant; import com.atguigu.tingshu.common.constant.RedisConstant; import com.atguigu.tingshu.common.constant.SystemConstant; import com.atguigu.tingshu.common.service.KafkaService; import com.atguigu.tingshu.common.util.MongoUtil; import com.atguigu.tingshu.model.user.UserListenProcess; import com.atguigu.tingshu.user.service.UserListenProcessService; import com.atguigu.tingshu.vo.album.TrackStatMqVo; import com.atguigu.tingshu.vo.user.UserListenProcessVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Date; import java.util.concurrent.TimeUnit; @Service @SuppressWarnings({"all"}) public class UserListenProcessServiceImpl implements UserListenProcessService { @Autowired private MongoTemplate mongoTemplate; /** * 获取当前用户收听声音播放进度 * * @param userId 用户ID * @param trackId 声音ID * @return */ @Override public BigDecimal getTrackBreakSecond(Long userId, Long trackId) { //1.构建查询条件 Query query = new Query(); query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId)); //2.执行查询播放进度 UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); if (userListenProcess != null) { return userListenProcess.getBreakSecond(); } return new BigDecimal("0.00"); } } ![image-20240307200116030](assets/image-20240307200116030.png) ## 3.2 更新播放进度 页面每隔10秒左右更新播放进度. 1. 更新播放进度页面会传递 专辑Id ,秒数,声音Id 。后台会将这个三个属性封装到UserListenProcessVo 对象中。然后利用MongoDB进行存储到UserListenProcess实体类中! 2. 为了提高用户快速访问,将用户信息存储到缓存中。先判断当前用户Id 与 声音Id 是否存在,不存在的话才将数据存储到缓存,并且要发送消息给kafka。 3. kafka 监听消息并消费,更新专辑与声音的统计数据。 ### 3.2.1 更新MongoDB ![](assets/tingshu015.png) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/73 在 **UserListenProcessApiController** 控制器中添加 java /** * 更新当前用户收听声音播放进度 * @param userListenProcessVo * @return */ @GuiGuLogin(required = false) @Operation(summary = "更新当前用户收听声音播放进度") @PostMapping("/userListenProcess/updateListenProcess") public Result updateListenProcess(@RequestBody UserListenProcessVo userListenProcessVo){ Long userId = AuthContextHolder.getUserId(); if (userId != null) { userListenProcessService.updateListenProcess(userId, userListenProcessVo); } return Result.ok(); } **UserListenProcessService**接口: java /** * 更新当前用户收听声音播放进度 * @param userId 用户ID * @param userListenProcessVo 播放进度信息 * @return */ void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo); **UserListenProcessServiceImpl**实现类: java @Autowired private RedisTemplate redisTemplate; @Autowired private KafkaService kafkaService; /** * 更新当前用户收听声音播放进度 * * @param userId 用户ID * @param userListenProcessVo 播放进度信息 * @return */ @Override public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) { //1.根据用户ID+声音ID获取播放进度 Query query = new Query(); //1.1 设置查询条件 query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId())); //1.2 设置查询第一条记录(避免小程序暂停后恢复播放将积压更新进度请求并发发起,导致新增多条播放进度) query.limit(1); UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); if (userListenProcess == null) { //2.如果播放进度不存在-新增播放进度 userListenProcess = new UserListenProcess(); userListenProcess.setUserId(userId); userListenProcess.setAlbumId(userListenProcessVo.getAlbumId()); userListenProcess.setTrackId(userListenProcessVo.getTrackId()); userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond()); userListenProcess.setIsShow(1); userListenProcess.setCreateTime(new Date()); userListenProcess.setUpdateTime(new Date()); } else { //3.如果播放进度存在-更新进度 userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond()); userListenProcess.setUpdateTime(new Date()); } mongoTemplate.save(userListenProcess, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); //4.采用Redis提供set k v nx ex 确保在规定时间内(24小时/当日内)播放进度统计更新1次 String key = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + userId + ":" + userListenProcessVo.getTrackId(); long ttl = DateUtil.endOfDay(new Date()).getTime() - System.currentTimeMillis(); Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, userListenProcess.getTrackId(), ttl, TimeUnit.MILLISECONDS); if (flag) { //5.如果是首次更新播放进度,发送消息到Kafka话题 //5.1 构建更新声音播放进度MQVO对象 TrackStatMqVo mqVo = new TrackStatMqVo(); //生成业务唯一标识,消费者端(专辑服务、搜索服务)用来做幂等性处理,确保一个消息只能只被处理一次 mqVo.setBusinessNo(IdUtil.fastSimpleUUID()); mqVo.setAlbumId(userListenProcessVo.getAlbumId()); mqVo.setTrackId(userListenProcessVo.getTrackId()); mqVo.setStatType(SystemConstant.TRACK_STAT_PLAY); mqVo.setCount(1); //5.2 发送消息到更新声音统计话题中 kafkaService.sendMessage(KafkaConstant.QUEUE_TRACK_STAT_UPDATE, JSON.toJSONString(mqVo)); } } ### 3.2.2 更新MySQL统计信息 在service-album 微服务中添加监听消息: java package com.atguigu.tingshu.album.receiver; import com.alibaba.fastjson.JSON; import com.atguigu.tingshu.album.service.AlbumInfoService; import com.atguigu.tingshu.common.constant.KafkaConstant; import com.atguigu.tingshu.vo.album.TrackStatMqVo; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component; /** * @author: atguigu * @create: 2023-12-19 15:31 */ @Slf4j @Component public class AlbumReceiver { @Autowired private AlbumInfoService albumInfoService; /** * 监听到更新声音统计信息 * 1.考虑消息幂等性 2.是否需要事务管理 * * @param record */ @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE) public void updateTrackStat(ConsumerRecord<String, String> record) { String value = record.value(); if (StringUtils.isNotBlank(value)) { log.info("[专辑服务],监听到更新声音统计消息:{}", value); TrackStatMqVo mqVo = JSON.parseObject(value, TrackStatMqVo.class); albumInfoService.updateTrackStat(mqVo); } } } 在**TrackInfoService** 中添加接口 java /** * MQ监听更新声音统计信息 * @param mqVo */ void updateTrackStat(TrackStatMqVo mqVo); 在**TrackInfoServiceImpl** 中添加实现 java @Autowired private AlbumStatMapper albumStatMapper; @Autowired private RedisTemplate redisTemplate; /** * MQ监听更新声音统计信息(包含:播放、收藏、点赞、评论) * * @param mqVo */ @Override @Transactional(rollbackFor = Exception.class) public void updateTrackStat(TrackStatMqVo mqVo) { //1.做幂等性处理,统一个消息只处理一次 采用set k(业务消息唯一标识) v NX EX String key = "mq:" + mqVo.getBusinessNo(); try { Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, mqVo.getBusinessNo(), 1, TimeUnit.HOURS); if (flag) { //2.更新声音统计信息 trackStatMapper.updateStat(mqVo.getTrackId(), mqVo.getStatType(), mqVo.getCount()); //3.更新专辑统计信息(播放量、评论量只要声音+1,对应专辑也得+1) if (SystemConstant.TRACK_STAT_PLAY.equals(mqVo.getStatType())) { albumStatMapper.updateStat(mqVo.getAlbumId(), SystemConstant.ALBUM_STAT_PLAY, mqVo.getCount()); } if (SystemConstant.TRACK_STAT_COMMENT.equals(mqVo.getStatType())) { albumStatMapper.updateStat(mqVo.getAlbumId(), SystemConstant.ALBUM_STAT_COMMENT, mqVo.getCount()); } } } catch (Exception e) { //如果更新数据库发送异常,事务会进行回滚,下次再次投递消息允许继续处理统一个消息 redisTemplate.delete(key); throw new RuntimeException(e); } } **TrackStatMapper**.java 添加方法 java package com.atguigu.tingshu.album.mapper; import com.atguigu.tingshu.model.album.TrackStat; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.*; @Mapper public interface TrackStatMapper extends BaseMapper<TrackStat> { /** * 更新声音统计信息 * @param trackId 声音ID * @param statType 统计类型 * @param count 数量 */ @Update("update track_stat set stat_num = stat_num + #{count} where track_id = #{trackId} and stat_type = #{statType}") void updateStat(@Param("trackId") Long trackId, @Param("statType") String statType, @Param("count") Integer count); } **AlbumStatMapper**.java 接口添加 java package com.atguigu.tingshu.album.mapper; import com.atguigu.tingshu.model.album.AlbumStat; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; @Mapper public interface AlbumStatMapper extends BaseMapper<AlbumStat> { @Update("update album_stat set stat_num = stat_num + #{count} where album_id = #{albumId} and stat_type = #{statType}") void updateStat(@Param("albumId") Long albumId, @Param("statType") String statType, @Param("count") Integer count); } ## 3.3 专辑上次播放专辑声音 ![image-20231012111356796](assets/image-20231012111356796.png) 我们需要根据用户Id 来获取播放记录 ,需要获取到专辑Id 与声音Id 封装到map中然后返回数据即可! > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/83 控制器 **UserListenProcessApiController** java /** * 获取当前用户上次播放专辑声音记录 * * @return */ @GuiGuLogin @GetMapping("/userListenProcess/getLatelyTrack") public Result<Map<String, Long>> getLatelyTrack() { Long userId = AuthContextHolder.getUserId(); return Result.ok(userListenProcessService.getLatelyTrack(userId)); } **UserListenProcessService接口:** java /** * 获取用户最近一次播放记录 * @param userId * @return */ Map<String, Long> getLatelyTrack(Long userId); **UserListenProcessServiceImpl实现类**: java /** * 获取用户最近一次播放记录 * * @param userId * @return */ @Override public Map<String, Long> getLatelyTrack(Long userId) { //根据用户ID查询播放进度集合,按照更新时间倒序,获取第一条记录 //1.构建查询条件对象 Query query = new Query(); //1.1 封装用户ID查询条件 query.addCriteria(Criteria.where("userId").is(userId)); //1.2 按照更新时间排序 query.with(Sort.by(Sort.Direction.DESC, "updateTime")); //1.3 只获取第一条记录 query.limit(1); //2.执行查询 UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); if (listenProcess != null) { //封装响应结果 Map<String, Long> mapResult = new HashMap<>(); mapResult.put("albumId", listenProcess.getAlbumId()); mapResult.put("trackId", listenProcess.getTrackId()); return mapResult; } return null; } ## 3.4 获取声音统计信息 ![](assets/tingshu014.png) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/75 统计声音需要更新的数据如下,我们将数据封装到一个实体类中便于操作 java @Data @Schema(description = "用户声音统计信息") public class TrackStatVo { @Schema(description = "播放量") private Integer playStatNum; @Schema(description = "订阅量") private Integer collectStatNum; @Schema(description = "点赞量") private Integer praiseStatNum; @Schema(description = "评论数") private Integer commentStatNum; //该属性需要修改 } 在**TrackInfoApiController** 控制器中添加 java /** * 根据声音ID,获取声音统计信息 * @param trackId * @return */ @Operation(summary = "根据声音ID,获取声音统计信息") @GetMapping("/trackInfo/getTrackStatVo/{trackId}") public Result<TrackStatVo> getTrackStatVo(@PathVariable Long trackId){ return Result.ok(trackInfoService.getTrackStatVo(trackId)); } **TrackInfoService接口**: java /** * 根据声音ID,查询声音统计信息 * @param trackId * @return */ TrackStatVo getTrackStatVo(Long trackId); **TrackInfoServiceImpl实现类**: java /** * 根据声音ID,查询声音统计信息 * @param trackId * @return */ @Override public TrackStatVo getTrackStatVo(Long trackId) { return trackInfoMapper.getTrackStatVo(trackId); } **TrackInfoMapper**.java java /** * 获取声音统计信息 * @param trackId * @return */ @Select("select\n" + " track_id,\n" + " max(if(stat_type='0701', stat_num, 0)) playStatNum,\n" + " max(if(stat_type='0702', stat_num, 0)) collectStatNum,\n" + " max(if(stat_type='0703', stat_num, 0)) praiseStatNum,\n" + " max(if(stat_type='0704', stat_num, 0)) commentStatNum\n" + " from track_stat where track_id = #{trackId} and is_deleted=0\n" + "group by track_id") TrackStatVo getTrackStatVo(@Param("trackId") Long trackId); **SQL** sql # 根据声音ID查询指定声音统计信息 playStatNum collectStatNum praiseStatNum commentStatNum select track_id, max(if(stat_type='0701', stat_num, 0)) playStatNum, max(if(stat_type='0702', stat_num, 0)) collectStatNum, max(if(stat_type='0703', stat_num, 0)) praiseStatNum, max(if(stat_type='0704', stat_num, 0)) commentStatNum from track_stat where track_id = 49162 and is_deleted=0 group by track_id # 4、更新Redis排行榜 手动调用一次更新,查看排行榜。后续会整合xxl-job 分布式定时任务调度框架做定时调用。 ![详情-排行榜](assets/详情-排行榜.gif) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/77 service-album 微服务中**BaseCategoryApiController**控制器中添加 java /** * 查询所有一级分类列表 * @return */ @Operation(summary = "查询所有一级分类列表") @GetMapping("/category/findAllCategory1") public Result> getAllCategory1() { return Result.ok(baseCategoryService.list()); } **AlbumFeignClient** java /** * 查询所有一级分类列表 * @return */ @GetMapping("/category/findAllCategory1") public Result> getAllCategory1(); **AlbumDegradeFeignClient熔断类**: java @Override public Result> getAllCategory1() { log.error("[专辑模块Feign调用]getAllCategory1异常"); return null; } > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/79 在**SearchApiController** 中添加控制器 java /** * 为定时更新首页排行榜提供调用接口 * @return */ @Operation(summary = "为定时更新首页排行榜提供调用接口") @GetMapping("/albumInfo/updateLatelyAlbumRanking") public Result updateLatelyAlbumRanking(){ searchService.updateLatelyAlbumRanking(); return Result.ok(); } **SearchService**接口: java /** * 获取不同分类下不同排序方式榜单专辑列表 */ void updateLatelyAlbumRanking(); **SearchServiceImpl实现类:** java @Autowired private RedisTemplate redisTemplate; /** * 获取不同分类下不同排序方式榜单专辑列表 */ @Override public void updateLatelyAlbumRanking() { try { //1.远程调用专辑服务获取所有1级分类列表 List<BaseCategory1> category1List = albumFeignClient.getdAllCategory1().getData(); Assert.notNull(category1List, "一级分类为空"); //2.循环遍历1级分类列表,获取该分类下5种不同排序方式榜单专辑 for (BaseCategory1 baseCategory1 : category1List) { Long category1Id = baseCategory1.getId(); //3.在处理当前1级分类中,再次循环5种不同排序方式得到具体榜单数据 //3.1 声明排序方式数组 String[] rankingDimensionArray = new String[]{"hotScore", "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"}; for (String rankingDimension : rankingDimensionArray) { //3.2 调用ES检索接口获取榜单数据 SearchResponse<AlbumInfoIndex> searchResponse = elasticsearchClient.search( s -> s.index(INDEX_NAME) .query(q -> q.term(t -> t.field("category1Id").value(category1Id))) .sort(sort -> sort.field(f -> f.field(rankingDimension).order(SortOrder.Desc))) .size(10) , AlbumInfoIndex.class ); //3.3 获取当前分类下某个排序方式榜单专辑列表 List<Hit<AlbumInfoIndex>> hits = searchResponse.hits().hits(); if (CollectionUtil.isNotEmpty(hits)) { List<AlbumInfoIndex> list = hits.stream().map(hit -> hit.source()).collect(Collectors.toList()); //4.将榜单专辑列表存入Redis-Hash中 //4.1 声明Redis排行榜Hash接口 Key 形式:前缀+1级分类ID field:排序方式 val:榜单列表 String key = RedisConstant.RANKING_KEY_PREFIX + category1Id; //4.2 将当前分类榜单数据放入Redis中 redisTemplate.opsForHash().put(key, rankingDimension, list); } } } } catch (Exception e) { log.error("[搜索服务]更新排行榜异常:{}", e); throw new RuntimeException(e); } } # 5、获取排行榜 ![image-20231012114420751](assets/image-20231012114420751.png) 点击排行榜的时候,能看到获取排行榜的地址 排行榜:key=ranking:category1Id field = hotScore 或 playStatNum 或 subscribeStatNum 或 buyStatNum 或albumCommentStatNum value=List<AlbumInfoIndexVo> ![](assets/tingshu016.png) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/81 **SearchApiController** 控制器中添加 java /** * 获取指定1级分类下不同排序方式榜单列表-从Redis中获取 * @param category1Id * @param dimension * @return */ @Operation(summary = "获取指定1级分类下不同排序方式榜单列表") @GetMapping("/albumInfo/findRankingList/{category1Id}/{dimension}") public Result> getRankingList(@PathVariable Long category1Id, @PathVariable String dimension){ List<AlbumInfoIndex> list = searchService.getRankingList(category1Id, dimension); return Result.ok(list); } **SearchService**接口: java /** * 获取指定1级分类下不同排序方式榜单列表-从Redis中获取 * @param category1Id * @param dimension * @return */ List<AlbumInfoIndex> getRankingList(Long category1Id, String dimension); **SearchServiceImpl实现类**: java /** * 获取指定1级分类下不同排序方式榜单列表-从Redis中获取 * * @param category1Id * @param dimension * @return */ @Override public List<AlbumInfoIndex> getRankingList(Long category1Id, String dimension) { //1.构建分类排行榜Hash结构Key String key = RedisConstant.RANKING_KEY_PREFIX + category1Id; //2.获取Redis中hash结构中value Boolean flag = redisTemplate.opsForHash().hasKey(key, dimension); if (flag) { List<AlbumInfoIndex> list = (List) redisTemplate.opsForHash().get(key, dimension); return list; } return null; } 如何向别人介绍这个模块的设计思路】

Also create a ControllerMoreBook class that extends Controller.The moreBook method takes the name of a user and a number of books (as a string) as arguments. The moreBook method of the controller then transforms the number of books from a string to an integer (using the Integer.parseInt static method) and calls the moreBook method of the library to increase the number of books borrowed or lent by the user (depending on what kind of user it is) of a specific user, by the given argument. • If no exception occurs then the moreBook method of the controller returns the empty string. • If the moreBook method of the library throws an UnknownUserException then the moreBook method of the controller must catch this exception and return as result the error message from the exception object. • If the moreBook method of the library throws a NotALenderException then the moreBook method of the controller must catch this exception and return as result the error message from the exception object. • If the parseInt method of the Integer class throws a NumberFormatException (because the user typed something which is not an integer) then the moreBook method of the controller must catch this exception and return as result the error message from the exception object. Note: to keep things simple, it is allowed for a user of your system to increase the number of books of a user by a negative number, so there is no need to check for that. Modify the run method of the GUI class to add a ViewMoreBook view that uses a ControllerMoreBook controller and the same model as before (not a new model!) Do not delete the previous views. Run your GUI and check that you can correctly use the new view to increase the number of books for different users of your library (obviously your library must have some users in it to test this: see the last paragraph of Question 7). • Check that, when you increase a user’s book, the simple view is automatically correctly updated to show the new total number of borrowed books for all users of the library. • Also use the “get book” view to check that the user’s book value correctly changed. • Also check that increasing the book number of an unknown user correctly shows an error message.Also check that increasing the book of a user by a large negative number correctly shows an error message. Also check that trying to increase the book of a user by a number which is not an integer correctly shows an error message (do not worry about the content of the error message). 完成符合以上要求的java代码

package com.youlai.system.model.algori.controller; import com.youlai.system.model.algori.STFT; import org.springframework.web.bind.annotation.*; import java.io.File; import java.nio.charset.StandardCharsets; /** * STFT音频处理控制器 * 提供RESTful API接口实现音频分析功能 */ @RestController @RequestMapping("/api/stft") public class STFTController { static { try { System.out.println("JVM架构: " + System.getProperty("sun.arch.data.model") + "位"); System.setProperty("java.library.path", "src/main/resources/lib"); System.out.println("库路径: " + System.getProperty("java.library.path")); } catch (Exception e) { System.err.println("库路径配置失败: " + e.getMessage()); } } // 注入STFT库实例 private final STFT stftLibary = STFT.getInstance(); /** * 计算短时傅里叶变换 * @param filepath 音频文件路径(默认值:1-1.csv) * @param frameSize 帧长(默认值:256) * @param frameShift 帧移(默认值:128) * @param sampleRate 采样率(默认值:400.0) * @param windowType 窗类型(默认值:0) * @return 计算结果指针 */ @GetMapping("/compute") public String computeSTFT( @RequestParam(name = "filepath", defaultValue = "src/main/resources/1-1.csv") String filepath, @RequestParam(name = "frame_size", defaultValue = "256") int frameSize, @RequestParam(name = "frame_shift", defaultValue = "128") int frameShift, @RequestParam(name = "sample_rate", defaultValue = "400.0") double sampleRate, @RequestParam(name = "window_type", defaultValue = "0") int windowType) { // 添加文件路径验证 File file = new File(filepath); if (!file.exists()) { System.err.println("文件不存在: " + file.getAbsolutePath()); return "计算失败: 文件不存在"; } if (!file.canRead()) { System.err.println("无读取权限: " + file.getAbsolutePath()); return "计算失败: 无文件读取权限"; } // 添加编码验证 if (!filepath.equals(new String(filepath.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8))) { System.err.println("文件路径包含非UTF-8字符: " + filepath); return "计算失败: 文件路径包含非法字符"; } long resultPtr = 0; try { // 调用本地方法计算STFT resultPtr = stftLibary.compute_stft( filepath, frameSize, frameShift, sampleRate, windowType ); // 释放结果内存 if (resultPtr == 0) { return "计算失败,结果为空"; } } catch (Exception e) { // 异常处理 System.err.println("STFT计算异常: " + e.getMessage()); e.printStackTrace(); return "计算失败: " + e.getMessage(); }finally { stftLibary.freeResult(resultPtr); } return "计算成功"; } }当我获取了dll返回的指针后该如何读取其中的数据'

最新推荐

recommend-type

新能源车电机控制器:基于TI芯片的FOC算法源代码与实际应用

内容概要:本文详细介绍了基于TI芯片的FOC(场向量控制)算法在新能源车电机控制器中的应用。文章首先阐述了新能源车电机控制器的重要性及其对车辆性能的影响,接着深入探讨了FOC算法的工作原理,强调其在提高电机控制精度和能效方面的优势。随后,文章展示了完整的源代码资料,涵盖采样模块、CAN通信模块等多个关键部分,并指出这些代码不仅限于理论演示,而是来自实际量产的应用程序。此外,文中还特别提到代码遵循严格的规范,有助于读者理解和学习电机控制软件的最佳实践。 适合人群:从事新能源车研发的技术人员、电机控制工程师、嵌入式系统开发者以及对电机控制感兴趣的电子工程学生。 使用场景及目标:① 学习并掌握基于TI芯片的FOC算法的具体实现;② 理解电机控制器各模块的功能和交互方式;③ 提升实际项目开发能力,减少开发过程中遇到的问题。 其他说明:本文提供的源代码资料来源于早期已量产的新能源车控制器,因此具有较高的实用价值和参考意义。
recommend-type

中证500指数成分股历年调整名单2007至2023年 调入调出

中证500指数是中证指数有限公司开发的指数,样本空间内股票由全部A股中剔除沪深300指数成分股及总市值排名前300名的股票后,选取总市值排名靠前的500只股票组成,综合反映中国A股市场中一批中小市值公司的股票价格表现。包含字段:公告日期、变更日期、成份证券代码、成份证券简称、变动方式。各次调整日期:2006-12-26、2007-01-15、2007-06-01、2007-07-02、2007-12-10、2008-01-02、2008-06-04、2008-07-01、2008-12-15、2009-01-05、2009-05-05、2009-05-06、2009-06-15、2009-07-01、2009-08-10、2009-08-10。资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
recommend-type

掌握XFireSpring整合技术:HELLOworld原代码使用教程

标题:“xfirespring整合使用原代码”中提到的“xfirespring”是指将XFire和Spring框架进行整合使用。XFire是一个基于SOAP的Web服务框架,而Spring是一个轻量级的Java/Java EE全功能栈的应用程序框架。在Web服务开发中,将XFire与Spring整合能够发挥两者的优势,例如Spring的依赖注入、事务管理等特性,与XFire的简洁的Web服务开发模型相结合。 描述:“xfirespring整合使用HELLOworld原代码”说明了在这个整合过程中实现了一个非常基本的Web服务示例,即“HELLOworld”。这通常意味着创建了一个能够返回"HELLO world"字符串作为响应的Web服务方法。这个简单的例子用来展示如何设置环境、编写服务类、定义Web服务接口以及部署和测试整合后的应用程序。 标签:“xfirespring”表明文档、代码示例或者讨论集中于XFire和Spring的整合技术。 文件列表中的“index.jsp”通常是一个Web应用程序的入口点,它可能用于提供一个用户界面,通过这个界面调用Web服务或者展示Web服务的调用结果。“WEB-INF”是Java Web应用中的一个特殊目录,它存放了应用服务器加载的Servlet类文件和相关的配置文件,例如web.xml。web.xml文件中定义了Web应用程序的配置信息,如Servlet映射、初始化参数、安全约束等。“META-INF”目录包含了元数据信息,这些信息通常由部署工具使用,用于描述应用的元数据,如manifest文件,它记录了归档文件中的包信息以及相关的依赖关系。 整合XFire和Spring框架,具体知识点可以分为以下几个部分: 1. XFire框架概述 XFire是一个开源的Web服务框架,它是基于SOAP协议的,提供了一种简化的方式来创建、部署和调用Web服务。XFire支持多种数据绑定,包括XML、JSON和Java数据对象等。开发人员可以使用注解或者基于XML的配置来定义服务接口和服务实现。 2. Spring框架概述 Spring是一个全面的企业应用开发框架,它提供了丰富的功能,包括但不限于依赖注入、面向切面编程(AOP)、数据访问/集成、消息传递、事务管理等。Spring的核心特性是依赖注入,通过依赖注入能够将应用程序的组件解耦合,从而提高应用程序的灵活性和可测试性。 3. XFire和Spring整合的目的 整合这两个框架的目的是为了利用各自的优势。XFire可以用来创建Web服务,而Spring可以管理这些Web服务的生命周期,提供企业级服务,如事务管理、安全性、数据访问等。整合后,开发者可以享受Spring的依赖注入、事务管理等企业级功能,同时利用XFire的简洁的Web服务开发模型。 4. XFire与Spring整合的基本步骤 整合的基本步骤可能包括添加必要的依赖到项目中,配置Spring的applicationContext.xml,以包括XFire特定的bean配置。比如,需要配置XFire的ServiceExporter和ServicePublisher beans,使得Spring可以管理XFire的Web服务。同时,需要定义服务接口以及服务实现类,并通过注解或者XML配置将其关联起来。 5. Web服务实现示例:“HELLOworld” 实现一个Web服务通常涉及到定义服务接口和服务实现类。服务接口定义了服务的方法,而服务实现类则提供了这些方法的具体实现。在XFire和Spring整合的上下文中,“HELLOworld”示例可能包含一个接口定义,比如`HelloWorldService`,和一个实现类`HelloWorldServiceImpl`,该类有一个`sayHello`方法返回"HELLO world"字符串。 6. 部署和测试 部署Web服务时,需要将应用程序打包成WAR文件,并部署到支持Servlet 2.3及以上版本的Web应用服务器上。部署后,可以通过客户端或浏览器测试Web服务的功能,例如通过访问XFire提供的服务描述页面(WSDL)来了解如何调用服务。 7. JSP与Web服务交互 如果在应用程序中使用了JSP页面,那么JSP可以用来作为用户与Web服务交互的界面。例如,JSP可以包含JavaScript代码来发送异步的AJAX请求到Web服务,并展示返回的结果给用户。在这个过程中,JSP页面可能使用XMLHttpRequest对象或者现代的Fetch API与Web服务进行通信。 8. 项目配置文件说明 项目配置文件如web.xml和applicationContext.xml分别在Web应用和服务配置中扮演关键角色。web.xml负责定义Web组件,比如Servlet、过滤器和监听器,而applicationContext.xml则负责定义Spring容器中的bean,包括数据源、事务管理器、业务逻辑组件和服务访问器等。 总之,通过上述整合使用原代码的知识点,可以深入理解XFire与Spring框架的结合使用,以及如何开发和部署基本的Web服务。这些技术知识有助于进行更高层次的Web服务开发,以及在复杂的IT环境中灵活运用各种框架和工具。
recommend-type

【Unity2018汉化大揭秘】:一步到位优化中文用户体验

# 摘要 本论文详细介绍了Unity2018汉化项目的实施过程,从理论准备到实践步骤,再到后期的测试与优化,最终分享了汉化经验和心得。首先,强调了汉化项目对于用户体验提升和产品国际化的重要性,并分析了汉化资源的分类、识别与管理方法。接着,详细阐述了汉化工具的选择、脚本编写、资源手动调整等实践步骤,以及汉化质量测试、体验优化和项目维护更新的重要性。论文最后通过案例研究,分析了汉化中的挑战和应对策略,并预测了汉化技术未来的发展方向。整个汉化过程不仅涉及技术层面的操作,还包含了深入的理论研究和实践心得分享,对提升汉化项目的效率和质量具有指导意义。 # 关键字 Unity汉化;用户体验;国际化;资源
recommend-type

iPhone

<think>我们注意到用户意图不明确,但提到了“照片提取”和“其他功能帮助”。因此,我们需要通过搜索来获取关于iPhone照片提取的常见方法以及其他可能的功能帮助。由于用户问题比较宽泛,我们将重点放在照片提取上,因为这是明确提到的关键词。同时,我们也会考虑一些其他常用功能的帮助。首先,针对照片提取,可能涉及从iPhone导出照片、从备份中提取照片、或者从损坏的设备中恢复照片等。我们将搜索这些方面的信息。其次,关于其他功能帮助,我们可以提供一些常见问题的快速指南,如电池优化、屏幕时间管理等。根据要求,我们需要将答案组织为多个方法或步骤,并在每个步骤间换行。同时,避免使用第一人称和步骤词汇。由于
recommend-type

驾校一点通软件:提升驾驶证考试通过率

标题“驾校一点通”指向的是一款专门为学员考取驾驶证提供帮助的软件,该软件强调其辅助性质,旨在为学员提供便捷的学习方式和复习资料。从描述中可以推断出,“驾校一点通”是一个与驾驶考试相关的应用软件,这类软件一般包含驾驶理论学习、模拟考试、交通法规解释等内容。 文件标题中的“2007”这个年份标签很可能意味着软件的最初发布时间或版本更新年份,这说明了软件具有一定的历史背景和可能经过了多次更新,以适应不断变化的驾驶考试要求。 压缩包子文件的文件名称列表中,有以下几个文件类型值得关注: 1. images.dat:这个文件名表明,这是一个包含图像数据的文件,很可能包含了用于软件界面展示的图片,如各种标志、道路场景等图形。在驾照学习软件中,这类图片通常用于帮助用户认识和记忆不同交通标志、信号灯以及驾驶过程中需要注意的各种道路情况。 2. library.dat:这个文件名暗示它是一个包含了大量信息的库文件,可能包含了法规、驾驶知识、考试题库等数据。这类文件是提供给用户学习驾驶理论知识和准备科目一理论考试的重要资源。 3. 驾校一点通小型汽车专用.exe:这是一个可执行文件,是软件的主要安装程序。根据标题推测,这款软件主要是针对小型汽车驾照考试的学员设计的。通常,小型汽车(C1类驾照)需要学习包括车辆构造、基础驾驶技能、安全行车常识、交通法规等内容。 4. 使用说明.html:这个文件是软件使用说明的文档,通常以网页格式存在,用户可以通过浏览器阅读。使用说明应该会详细介绍软件的安装流程、功能介绍、如何使用软件的各种模块以及如何通过软件来帮助自己更好地准备考试。 综合以上信息,我们可以挖掘出以下几个相关知识点: - 软件类型:辅助学习软件,专门针对驾驶考试设计。 - 应用领域:主要用于帮助驾考学员准备理论和实践考试。 - 文件类型:包括图片文件(images.dat)、库文件(library.dat)、可执行文件(.exe)和网页格式的说明文件(.html)。 - 功能内容:可能包含交通法规知识学习、交通标志识别、驾驶理论学习、模拟考试、考试题库练习等功能。 - 版本信息:软件很可能最早发布于2007年,后续可能有多个版本更新。 - 用户群体:主要面向小型汽车驾照考生,即C1类驾照学员。 - 使用方式:用户需要将.exe安装文件进行安装,然后根据.html格式的使用说明来熟悉软件操作,从而利用images.dat和library.dat中的资源来辅助学习。 以上知识点为从给定文件信息中提炼出来的重点,这些内容对于了解“驾校一点通”这款软件的功能、作用、使用方法以及它的发展历史都有重要的指导意义。
recommend-type

【DFLauncher自动化教程】:简化游戏启动流程,让游戏体验更流畅

# 摘要 DFLauncher是一个功能丰富的游戏启动和管理平台,本论文将介绍其安装、基础使用、高级设置、社区互动以及插件开发等方面。通过对配置文件的解析、界面定制、自动化功能的实现、高级配置选项、安全性和性能监控的详细讨论,本文阐述了DFLauncher如何帮助用户更高效地管理和优化游戏环境。此外,本文还探讨了DFLauncher社区的资源分享、教育教程和插件开发等内容,
recommend-type

自适应卡尔曼滤波是什么意思

<think>嗯,用户这次想深入了解自适应卡尔曼滤波(AKF)的概念和原理。从对话历史看,用户之前研究过相机自动对焦系统的降噪技术,其中提到过自适应卡尔曼滤波的应用场景。用户可能是个工程师或研究者,正在探索信号处理在具体场景的实现细节。 用户提供的三篇参考文献很有价值:[1]是基础理论综述,[2]聚焦多传感器场景,[3]讨论噪声协方差自适应方法。需要特别注意相机AF系统的特殊需求——实时性要求高(每秒数十次对焦计算)、噪声环境复杂(机械振动/弱光干扰),这些在解释原理时要结合具体案例。 技术要点需要分层解析:先明确标准卡尔曼滤波的局限(固定噪声参数),再展开自适应机制。对于相机AF场景,重
recommend-type

EIA-CEA 861B标准深入解析:时间与EDID技术

EIA-CEA 861B标准是美国电子工业联盟(Electronic Industries Alliance, EIA)和消费电子协会(Consumer Electronics Association, CEA)联合制定的一个技术规范,该规范详细规定了视频显示设备和系统之间的通信协议,特别是关于视频显示设备的时间信息(timing)和扩展显示识别数据(Extended Display Identification Data,简称EDID)的结构与内容。 在视频显示技术领域,确保不同品牌、不同型号的显示设备之间能够正确交换信息是至关重要的,而这正是EIA-CEA 861B标准所解决的问题。它为制造商提供了一个统一的标准,以便设备能够互相识别和兼容。该标准对于确保设备能够正确配置分辨率、刷新率等参数至关重要。 ### 知识点详解 #### EIA-CEA 861B标准的历史和重要性 EIA-CEA 861B标准是随着数字视频接口(Digital Visual Interface,DVI)和后来的高带宽数字内容保护(High-bandwidth Digital Content Protection,HDCP)等技术的发展而出现的。该标准之所以重要,是因为它定义了电视、显示器和其他显示设备之间如何交互时间参数和显示能力信息。这有助于避免兼容性问题,并确保消费者能有较好的体验。 #### Timing信息 Timing信息指的是关于视频信号时序的信息,包括分辨率、水平频率、垂直频率、像素时钟频率等。这些参数决定了视频信号的同步性和刷新率。正确配置这些参数对于视频播放的稳定性和清晰度至关重要。EIA-CEA 861B标准规定了多种推荐的视频模式(如VESA标准模式)和特定的时序信息格式,使得设备制造商可以参照这些标准来设计产品。 #### EDID EDID是显示设备向计算机或其他视频源发送的数据结构,包含了关于显示设备能力的信息,如制造商、型号、支持的分辨率列表、支持的视频格式、屏幕尺寸等。这种信息交流机制允许视频源设备能够“了解”连接的显示设备,并自动设置最佳的输出分辨率和刷新率,实现即插即用(plug and play)功能。 EDID的结构包含了一系列的块(block),其中定义了包括基本显示参数、色彩特性、名称和序列号等在内的信息。该标准确保了这些信息能以一种标准的方式被传输和解释,从而简化了显示设置的过程。 #### EIA-CEA 861B标准的应用 EIA-CEA 861B标准不仅适用于DVI接口,还适用于HDMI(High-Definition Multimedia Interface)和DisplayPort等数字视频接口。这些接口技术都必须遵循EDID的通信协议,以保证设备间正确交换信息。由于标准的广泛采用,它已经成为现代视频信号传输和显示设备设计的基础。 #### EIA-CEA 861B标准的更新 随着技术的进步,EIA-CEA 861B标准也在不断地更新和修订。例如,随着4K分辨率和更高刷新率的显示技术的发展,该标准已经扩展以包括支持这些新技术的时序和EDID信息。任何显示设备制造商在设计新产品时,都必须考虑最新的EIA-CEA 861B标准,以确保兼容性。 #### 结论 EIA-CEA 861B标准是电子显示领域的一个重要规范,它详细定义了视频显示设备在通信时所使用的信号时序和设备信息的格式。该标准的存在,使得不同厂商生产的显示设备可以无缝连接和集成,极大地增强了用户体验。对于IT专业人士而言,了解和遵守EIA-CEA 861B标准是进行视频系统设计、故障诊断及设备兼容性测试的重要基础。
recommend-type

【DFLauncher应用实战】:如何将DFLauncher融入矮人要塞并提升效率

# 摘要 DFLauncher是一款功能全面的游戏管理工具,旨在简化游戏安装、启动和维护过程。本文介绍了DFLauncher的基本使用方法,详细解析了其核心功能,包括游戏库管理、游戏配置优化、更新机制等。同时,文章探讨了DFLauncher在特定游戏“矮人要塞”中的集成应用,以及通过插件和脚本进行的高级定制。故障诊断与系统优化章节提供了实用的诊断方法和性能提升技巧。最后,本文展望了DFLauncher的未来发展方向,并鼓励社区贡献和用户反馈,以满足不断变化的用户需求。 # 关键字 DFLauncher;游戏管理工具;安装配置;性能优化;故障诊断;社区贡献;定制化扩展;网络功能集成 参考资源