course description
- Realize my favorite function
- Implement common user settings
- Implement the blacklist function
- Realize the function of modifying the mobile phone number
1. Statistics of my likes
In my module, the data related to "like" will be displayed in detail, as follows:
1.1. Concept description
- like
- I like others, such as: Zhang San likes Li Si, just like the data, it does not mean that Li Si also likes Zhang San.
- fan
- For Li Si, Zhang San is his fan.
- follow each other (like)
- If Li Si also likes Zhang San, then Zhang San and Li Si like each other.
1.2, dubbo service
1.2.1,UserLikeApi
//com.tanhua.dubbo.server.api.UserLikeApi /** * number of mutual likes * * @return */ Long queryMutualLikeCount(Long userId); /** * likes * * @return */ Long queryLikeCount(Long userId); /** * Number of fans * * @return */ Long queryFanCount(Long userId);
1.2.2,UserLikeApiImpl
//com.tanhua.dubbo.server.api.UserLikeApiImpl /** * Query the number of mutual likes * There are 2 ways to implement: the first one: query redis, the second one: query MongoDB * Suggestion: Use redis query first, then consider using Mongodb * * @param userId * @return */ @Override public Long queryMutualLikeCount(Long userId) { //Query my like list List<Long> likeUserIdList = this.queryLikeList(userId); Long count = 0L; for (Long likeUserId : likeUserIdList) { String redisKey = this.getLikeRedisKey(likeUserId); String hashKey = String.valueOf(userId); //Is "me" in the like list of "others" if (this.redisTemplate.opsForHash().hasKey(redisKey, hashKey)) { count++; } } return count; } @Override public Long queryLikeCount(Long userId) { String redisKey = this.getLikeRedisKey(userId); return this.redisTemplate.opsForHash().size(redisKey); } @Override public Long queryFanCount(Long userId) { //Cannot be done through redis query, must be queried from Mongodb Query query = Query.query(Criteria.where("likeUserId").is(userId)); return this.mongoTemplate.count(query, UserLike.class); }
1.2.3, unit test
package com.tanhua.dubbo.server.api; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class TestUserLikeApiImpl { @Autowired private UserLikeApi userLikeApi; @Test public void testQueryCounts(){ System.out.println(this.userLikeApi.queryEachLikeCount(1L)); System.out.println(this.userLikeApi.queryFanCount(1L)); System.out.println(this.userLikeApi.queryLikeCount(1L)); } }
1.3. APP interface service
Document address: https://mock-java.itheima.net/project/35/interface/api/899
1.3.1,CountsVo
package com.tanhua.server.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class CountsVo { private Long eachLoveCount; //like each other private Long loveCount; //like private Long fanCount; //fan }
1.3.2,UsersController
//com.tanhua.server.controller.MyCenterController /** * Mutual Likes, Likes, Followers - Statistics * * @return */ @GetMapping("counts") public ResponseEntity<CountsVo> queryCounts(){ try { CountsVo countsVo = this.myCenterService.queryCounts(); if(null != countsVo){ return ResponseEntity.ok(countsVo); } } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
1.3.3,UsersService
//com.tanhua.server.service.MyCenterService public CountsVo queryCounts() { User user = UserThreadLocal.get(); CountsVo countsVo = new CountsVo(); countsVo.setEachLoveCount(this.userLikeApi.queryMutualLikeCount(user.getId())); countsVo.setFanCount(this.userLikeApi.queryFanCount(user.getId())); countsVo.setLoveCount(this.userLikeApi.queryLikeCount(user.getId())); return countsVo; }
1.3.4. Test
2. Like list
Interface service: https://mock-java.itheima.net/project/35/interface/api/905
This interface integrates 4 interfaces, which are distinguished by type: 1 Follow each other 2 I follow 3 Followers 4 Who watched me
2.1, like dubbo interface service
2.1.1. Define interface
Define the method in the dubbo interface:
//com.tanhua.dubbo.server.api.UserLikeApi /** * Query Mutual Like List * * @param userId * @param page * @param pageSize * @return */ PageInfo<UserLike> queryMutualLikeList(Long userId, Integer page, Integer pageSize); /** * check my favorite list * * @param userId * @param page * @param pageSize * @return */ PageInfo<UserLike> queryLikeList(Long userId, Integer page, Integer pageSize); /** * Query fan list * * @param userId * @param page * @param pageSize * @return */ PageInfo<UserLike> queryFanList(Long userId, Integer page, Integer pageSize);
2.1.2, implement the interface
//com.tanhua.dubbo.server.api.UserLikeApiImpl @Override public PageInfo<UserLike> queryMutualLikeList(Long userId, Integer page, Integer pageSize) { //Query my like list List<Long> userLikeIdList = this.queryLikeList(userId); //Find people who like me Query query = Query.query(Criteria.where("userId").in(userLikeIdList) .and("likeUserId").is(userId) ); return this.queryList(query, page, pageSize); } @Override public PageInfo<UserLike> queryLikeList(Long userId, Integer page, Integer pageSize) { Query query = Query.query(Criteria.where("userId").is(userId)); return this.queryList(query, page, pageSize); } @Override public PageInfo<UserLike> queryFanList(Long userId, Integer page, Integer pageSize) { Query query = Query.query(Criteria.where("likeUserId").is(userId)); return this.queryList(query, page, pageSize); } private PageInfo<UserLike> queryList(Query query, Integer page, Integer pageSize) { //set pagination PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created"))); query.with(pageRequest); List<UserLike> userLikeList = this.mongoTemplate.find(query, UserLike.class); PageInfo<UserLike> pageInfo = new PageInfo<>(); pageInfo.setPageNum(page); pageInfo.setPageSize(pageSize); pageInfo.setRecords(userLikeList); return pageInfo; }
2.2. Recent visitor dubbo service
2.2.1. Define interface
//com.tanhua.dubbo.server.api.VisitorsApi /** * Sort in reverse chronological order to query recent visitor information * * @param userId * @param page * @param pageSize * @return */ PageInfo<Visitors> topVisitor(Long userId, Integer page, Integer pageSize);
2.2.2, Writing and implementing
//com.tanhua.dubbo.server.api.VisitorsApiImpl @Override public List<Visitors> queryMyVisitor(Long userId) { // Query the top 5 visitor data, sorted in reverse order of visit time // If the user has already queried the list, record the query time, and subsequent queries need to be queried backwards according to this time // The last time the list was queried Long date = Convert.toLong(this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, String.valueOf(userId))); PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date"))); Query query = Query.query(Criteria.where("userId").is(userId)) .with(pageRequest); if (ObjectUtil.isNotEmpty(date)) { query.addCriteria(Criteria.where("date").gte(date)); } return this.queryList(query, userId); } private List<Visitors> queryList(Query query, Long userId){ List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class); //Query the score of each visiting user for (Visitors visitors : visitorsList) { Query queryScore = Query.query(Criteria.where("toUserId") .is(userId).and("userId").is(visitors.getVisitorUserId()) ); RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class); if(ObjectUtil.isNotEmpty(recommendUser)){ visitors.setScore(recommendUser.getScore()); }else { //default score visitors.setScore(90d); } } return visitorsList; } @Override public PageInfo<Visitors> topVisitor(Long userId, Integer page, Integer pageSize) { PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date"))); Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest); List<Visitors> visitorsList = this.queryList(query, userId); PageInfo<Visitors> pageInfo = new PageInfo<>(); pageInfo.setPageNum(page); pageInfo.setPageSize(pageSize); pageInfo.setRecords(visitorsList); //Record the current time in redis, when you query on the home page, you can query after this time String redisKey = VISITOR_REDIS_KEY; String hashKey = String.valueOf(userId); String value = String.valueOf(System.currentTimeMillis()); this.redisTemplate.opsForHash().put(redisKey, hashKey, value); return pageInfo; }
2.3, APP interface service
Interface document: https://mock-java.itheima.net/project/35/interface/api/905
2.3.1,UserLikeListVo
package com.tanhua.server.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class UserLikeListVo { private Long id; private String avatar; private String nickname; private String gender; private Integer age; private String city; private String education; private Integer marriage; //Marital status (0 unmarried, 1 married) private Integer matchRate; //suitability private Boolean alreadyLove; //do you like ta }
2.3.2,MyCenterController
//com.tanhua.server.controller.MyCenterController /** * Mutual Follow, I Follow, Fans, Who Viewed Me - Flip List * * @param type 1 Follow each other 2 I follow 3 Followers 4 Who watched me * @param page * @param pageSize * @param nickname * @return */ @GetMapping("friends/{type}") public ResponseEntity<PageResult> queryLikeList(@PathVariable("type") String type, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "pagesize", defaultValue = "10") Integer pageSize, @RequestParam(value = "nickname", required = false) String nickname) { try { page = Math.max(1, page); PageResult pageResult = this.myCenterService.queryLikeList(Integer.valueOf(type), page, pageSize, nickname); return ResponseEntity.ok(pageResult); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
2.3.3,MyCenterService
//com.tanhua.server.service.MyCenterService public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickname) { PageResult pageResult = new PageResult(); pageResult.setPage(page); pageResult.setPagesize(pageSize); Long userId = UserThreadLocal.get().getId(); List<Object> userIdList = null; //1 Follow each other 2 I follow 3 Followers 4 Who watched me switch(type){ case 1:{ PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(userId, page, pageSize); userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId"); break; } case 2:{ PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(userId, page, pageSize); userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId"); break; } case 3:{ PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(userId, page, pageSize); userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId"); break; } case 4:{ PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(userId, page, pageSize); userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "visitorUserId"); break; } default: return pageResult; } if(CollUtil.isEmpty(userIdList)){ return pageResult; } QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.in("user_id", userIdList); if(StrUtil.isNotEmpty(nickname)){ queryWrapper.like("nick_name", nickname); } List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper); List<UserLikeListVo> userLikeListVos = new ArrayList<>(); for (UserInfo userInfo : userInfoList) { UserLikeListVo userLikeListVo = new UserLikeListVo(); userLikeListVo.setAge(userInfo.getAge()); userLikeListVo.setAvatar(userInfo.getLogo()); userLikeListVo.setCity(userInfo.getCity()); userLikeListVo.setEducation(userInfo.getEdu()); userLikeListVo.setGender(userInfo.getSex().name().toLowerCase()); userLikeListVo.setId(userInfo.getUserId()); userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "Married") ? 1 : 0); userLikeListVo.setNickname(userInfo.getNickName()); //Do you like isLike in userLikeApi open? userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(userId, userInfo.getUserId())); Double score = this.recommendUserService.queryScore(userId, userInfo.getUserId()); userLikeListVo.setMatchRate(Convert.toInt(score)); userLikeListVos.add(userLikeListVo); } pageResult.setItems(userLikeListVos); return pageResult; }
2.3.4. Test
2.4. Cancel like
The "unlike" operation can be performed in the list.
Interface document: https://mock-java.itheima.net/project/35/interface/api/923
2.4.1,MyCenterController
//com.tanhua.server.controller.MyCenterController /** * unlike * * @param userId * @return */ @DeleteMapping("like/{uid}") public ResponseEntity<Void> disLike(@PathVariable("uid") Long userId) { try { this.myCenterService.disLike(userId); return ResponseEntity.ok(null); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
2.4.2,MyCenterService
//com.tanhua.server.service.MyCenterService /** * unlike * * @param userId */ public void disLike(Long userId) { //Determine whether the current user and this user like each other User user = UserThreadLocal.get(); Boolean mutualLike = this.userLikeApi.isMutualLike(user.getId(), userId); //unlike this.userLikeApi.notLikeUser(user.getId(), userId); if(mutualLike){ //Cancel the friend relationship, cancel the friend relationship on the Huanxin platform this.imService.removeUser(userId); } }
2.4.3,IMService
//com.tanhua.server.service.IMService /** * delete friend * * @param userId friend id */ public void removeUser(Long userId) { //delete friendship User user = UserThreadLocal.get(); Boolean result = this.usersApi.removeUsers(user.getId(), userId); if(result){ //Cancel the friend relationship of Huanxin platform this.huanXinApi.removeUserFriend(user.getId(), userId); } }
2.4.4. Test
When testing, you need to clear the user_like table data in MongoDB and delete the like and dislike data in Redis.
Test with user 2, who is now friends with user 1:
Unlike:
2.5. Like fans
In viewing the fan list, you can perform "like operation" on fans.
Document address: https://mock-java.itheima.net/project/35/interface/api/917
2.5.1,MyCenterController
//com.tanhua.server.controller.MyCenterController /** * follow fans * * @param userId * @return */ @PostMapping("fans/{uid}") public ResponseEntity<Void> likeFan(@PathVariable("uid") Long userId){ try { this.myCenterService.likeFan(userId); return ResponseEntity.ok(null); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
2.5.2,MyCenterService
//com.tanhua.server.service.MyCenterService @Autowired private TanHuaService tanHuaService; /** * like * * @param userId */ public void likeFan(Long userId) { //Like users, if users like each other, they will become friends this.tanHuaService.likeUser(userId); }
2.5.3. Test
3. User general settings
3.1, table structure
CREATE TABLE `tb_settings` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) DEFAULT NULL, `like_notification` tinyint(4) DEFAULT '1' COMMENT 'push like notification', `pinglun_notification` tinyint(4) DEFAULT '1' COMMENT 'Push comment notification', `gonggao_notification` tinyint(4) DEFAULT '1' COMMENT 'Push announcement notification', `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='setting table';
3.2,pojo
my-tanhua-common project:
package com.tanhua.common.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Settings extends BasePojo { private Long id; private Long userId; private Boolean likeNotification = true; private Boolean pinglunNotification = true; private Boolean gonggaoNotification = true; }
3.3,SettingsMapper
package com.tanhua.common.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.tanhua.common.pojo.Settings; public interface SettingsMapper extends BaseMapper<Settings> { }
3.4,SettingsService
package com.tanhua.server.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.tanhua.common.mapper.SettingsMapper; import com.tanhua.common.pojo.Settings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SettingsService { @Autowired private SettingsMapper settingsMapper; /** * Query configuration based on user id * * @param userId * @return */ public Settings querySettings(Long userId) { QueryWrapper<Settings> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_id", userId); return this.settingsMapper.selectOne(queryWrapper); } }
3.5. Query Configuration
Document address: https://mock-java.itheima.net/project/35/interface/api/893
3.5.1,SettingsVo
package com.tanhua.server.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class SettingsVo { private Long id; //stranger problem private String strangerQuestion = ""; //Phone number private String phone; //push like notification private Boolean likeNotification = true; //Push comment notification private Boolean pinglunNotification = true; //Push announcement notification private Boolean gonggaoNotification = true; }
3.5.2,MyCenterController
//com.tanhua.server.controller.MyCenterController /** * query configuration * * @return */ @GetMapping("settings") public ResponseEntity<SettingsVo> querySettings() { try { SettingsVo settingsVo = this.myCenterService.querySettings(); if (null != settingsVo) { return ResponseEntity.ok(settingsVo); } } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
3.5.3,MyCenterService
//com.tanhua.server.service.MyCenterService public SettingsVo querySettings() { SettingsVo settingsVo = new SettingsVo(); User user = UserThreadLocal.get(); //Set the basic information of the user settingsVo.setId(user.getId()); settingsVo.setPhone(user.getMobile()); //Query user configuration data Settings settings = this.settingsService.querySettings(user.getId()); if(ObjectUtil.isNotEmpty(settings)){ settingsVo.setGonggaoNotification(settings.getGonggaoNotification()); settingsVo.setLikeNotification(settings.getLikeNotification()); settingsVo.setPinglunNotification(settings.getPinglunNotification()); } //Ask Strangers Questions settingsVo.setStrangerQuestion(this.tanHuaService.queryQuestion(user.getId())); return settingsVo; }
2.5.4. Test
3.6, save the stranger problem
Document address: https://mock-java.itheima.net/project/35/interface/api/929
3.6.1,MyCenterController
//com.tanhua.server.controller.MyCenterController /** * Set up stranger questions * * @return */ @PostMapping("questions") public ResponseEntity<Void> saveQuestions(@RequestBody Map<String, String> param) { try { String content = param.get("content"); this.myCenterService.saveQuestions(content); return ResponseEntity.ok(null); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
3.6.2,MyCenterService
//com.tanhua.server.service.MyCenterService public void saveQuestions(String content) { User user = UserThreadLocal.get(); this.questionService.save(user.getId(), content); }
3.6.3,QuestionService
//com.tanhua.server.service.QuestionService public void save(Long userId, String content) { Question question = this.queryQuestion(userId); if(null != question){ question.setTxt(content); this.questionMapper.updateById(question); }else { question = new Question(); question.setUserId(userId); question.setTxt(content); question.setCreated(new Date()); question.setUpdated(question.getCreated()); this.questionMapper.insert(question); } }
3.7. Blacklist list
The blacklist function can be used to judge when strangers say hello, if they are on the blacklist, they cannot say hello.
Interface document: https://mock-java.itheima.net/project/35/interface/api/935
3.7.1, table structure
CREATE TABLE `tb_black_list` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) DEFAULT NULL, `black_user_id` bigint(20) DEFAULT NULL, `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='blacklist'; --Test Data INSERT INTO `tb_black_list` (`id`, `user_id`, `black_user_id`, `created`, `updated`) VALUES ('1', '1', '22', '2019-11-01 15:47:22', '2019-11-01 15:47:24'); INSERT INTO `tb_black_list` (`id`, `user_id`, `black_user_id`, `created`, `updated`) VALUES ('2', '1', '23', '2019-11-01 15:47:39', '2019-11-01 15:47:42'); INSERT INTO `tb_black_list` (`id`, `user_id`, `black_user_id`, `created`, `updated`) VALUES ('3', '1', '24', '2019-11-01 15:47:51', '2019-11-01 15:47:56');
3.7.2,pojo
package com.tanhua.common.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class BlackList extends BasePojo { private Long id; private Long userId; private Long blackUserId; }
3.7.3,BlackListMapper
package com.tanhua.common.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.tanhua.common.pojo.BlackList; public interface BlackListMapper extends BaseMapper<BlackList> { }
3.7.4,BlackListService
package com.tanhua.server.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.tanhua.common.mapper.BlackListMapper; import com.tanhua.common.pojo.BlackList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BlackListService { @Autowired private BlackListMapper blackListMapper; public IPage<BlackList> queryBlacklist(Long userId, Integer page, Integer pageSize) { QueryWrapper<BlackList> wrapper = new QueryWrapper<BlackList>(); wrapper.eq("user_id", userId); wrapper.orderByDesc("created"); Page<BlackList> pager = new Page<>(page, pageSize); return this.blackListMapper.selectPage(pager, wrapper); } }
Configure the pagination plugin:
package com.tanhua.server.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { /** * paging plugin */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
3.7.5,BlackListVo
package com.tanhua.server.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class BlackListVo { private Long id; private String avatar; private String nickname; private String gender; private Integer age; }
3.7.6,MyCenterController
//com.tanhua.server.controller.MyCenterController /** * Query blacklist * * @param page * @param pagesize * @return */ @GetMapping("blacklist") public ResponseEntity<PageResult> queryBlacklist(@RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "pagesize", defaultValue = "10") Integer pagesize) { try { PageResult pageResult = this.myCenterService.queryBlacklist(page, pagesize); return ResponseEntity.ok(pageResult); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
3.7.7,MyCenterService
//com.tanhua.server.service.MyCenterService public PageResult queryBlacklist(Integer page, Integer pageSize) { User user = UserThreadLocal.get(); IPage<BlackList> blackListIPage = this.blackListService.queryBlacklist(user.getId(), page, pageSize); PageResult pageResult = new PageResult(); pageResult.setPage(page); pageResult.setPagesize(pageSize); pageResult.setCounts(Convert.toInt(blackListIPage.getTotal())); pageResult.setPages(Convert.toInt(blackListIPage.getPages())); List<BlackList> records = blackListIPage.getRecords(); if(CollUtil.isEmpty(records)){ return pageResult; } List<Object> userIds = CollUtil.getFieldValues(records, "blackUserId"); List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds); List<BlackListVo> blackListVos = new ArrayList<>(); for (UserInfo userInfo : userInfoList) { BlackListVo blackListVo = new BlackListVo(); blackListVo.setAge(userInfo.getAge()); blackListVo.setAvatar(userInfo.getLogo()); blackListVo.setGender(userInfo.getSex().name().toLowerCase()); blackListVo.setId(userInfo.getUserId()); blackListVo.setNickname(userInfo.getNickName()); blackListVos.add(blackListVo); } pageResult.setItems(blackListVos); return pageResult; }
3.7.8. Test
3.8. Remove the blacklist
Interface document: https://mock-java.itheima.net/project/35/interface/api/941
3.8.1,MyCenterController
/** * remove blacklist * * @return */ @DeleteMapping("blacklist/{uid}") public ResponseEntity<Void> delBlacklist(@PathVariable("uid") Long userId) { try { this.myCenterService.delBlacklist(userId); return ResponseEntity.ok(null); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
3.8.2,MyCenterService
public void delBlacklist(Long userId) { User user = UserThreadLocal.get(); this.blackListService.delBlacklist(user.getId(), userId); }
3.8.3,BlackListService
public Boolean delBlacklist(Long userId, Long blackUserId) { QueryWrapper<BlackList> wrapper = new QueryWrapper<BlackList>(); wrapper.eq("user_id", userId).eq("black_user_id", blackUserId); return this.blackListMapper.delete(wrapper) > 0; }
3.9. Update notice
Interface document: https://mock-java.itheima.net/project/35/interface/api/965
3.9.1,MyCenterController
//com.tanhua.server.controller.MyCenterController /** * Update notification settings * * @param param * @return */ @PostMapping("notifications/setting") public ResponseEntity<Void> updateNotification(@RequestBody Map<String, Boolean> param) { try { Boolean likeNotification = param.get("likeNotification"); Boolean pinglunNotification = param.get("pinglunNotification"); Boolean gonggaoNotification = param.get("gonggaoNotification"); this.myCenterService.updateNotification(likeNotification, pinglunNotification, gonggaoNotification); return ResponseEntity.ok(null); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
2.9.2,MyCenterService
//com.tanhua.server.service.MyCenterService public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) { User user = UserThreadLocal.get(); this.settingsService.updateNotification(user.getId(), likeNotification, pinglunNotification, gonggaoNotification); }
2.9.3,SettingsService
//com.tanhua.server.service.SettingsService public void updateNotification(Long userId, Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) { QueryWrapper<Settings> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_id", userId); Settings settings = this.settingsMapper.selectOne(queryWrapper); if(null == settings){ //If there is no data, insert a piece of data settings = new Settings(); settings.setUserId(userId); this.settingsMapper.insert(settings); }else{ //renew settings.setLikeNotification(likeNotification); settings.setPinglunNotification(pinglunNotification); settings.setGonggaoNotification(gonggaoNotification); this.settingsMapper.update(settings, queryWrapper); } }
3.10. Update mobile phone number
The logic of updating the mobile phone number is completed in the sso system. The process is: the old mobile phone number obtains the verification code, after the verification code is verified, the new mobile phone number is set, and finally the new mobile phone number is saved.
Step 1, send SMS verification code: https://mock-java.itheima.net/project/35/interface/api/947
Step 2, verify the verification code: https://mock-java.itheima.net/project/35/interface/api/953
Step 3, save the new phone number: https://mock-java.itheima.net/project/35/interface/api/959
Configure nginx:
location /users/phone { #All requests starting with /user/phone in the request path are forwarded to the sso system client_max_body_size 300m; #Set the maximum request body size to solve the problem that large files cannot be uploaded proxy_connect_timeout 300s; #Proxy connection timeout proxy_send_timeout 300s; #The timeout period for the agent to send data proxy_read_timeout 300s; #The timeout for the agent to read data proxy_pass http://127.0.0.1:18080; #forward request }
3.10.1. Send SMS verification code
MyCenterController:
//com.tanhua.sso.controller.MyCenterController /** * Send SMS verification code * * @return */ @PostMapping("phone/sendVerificationCode") public ResponseEntity<Void> sendVerificationCode(@RequestHeader("Authorization") String token) { try { boolean bool = this.myCenterService.sendVerificationCode(token); if (bool) { return ResponseEntity.ok(null); } } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
MyCenterService:
//com.tanhua.sso.service.MyCenterService package com.tanhua.sso.service; import com.tanhua.common.pojo.User; import com.tanhua.sso.vo.ErrorResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyCenterService { @Autowired private UserService userService; @Autowired private SmsService smsService; public Boolean sendVerificationCode(String token) { //check token User user = this.userService.queryUserByToken(token); if(ObjectUtil.isEmpty(user)){ return false; } ErrorResult errorResult = this.smsService.sendCheckCode(user.getMobile()); return errorResult == null; } }
3.10.2. Verification verification code
MyCenterController:
//com.tanhua.sso.controller.MyCenterController /** * Verify verification code * * @param param * @param token * @return */ @PostMapping("phone/checkVerificationCode") public ResponseEntity<Map<String, Object>> checkVerificationCode(@RequestBody Map<String, String> param, @RequestHeader("Authorization") String token) { try { String code = param.get("verificationCode"); Boolean bool = this.myCenterService.checkVerificationCode(code, token); Map<String, Object> result = new HashMap<>(); result.put("verification", bool); return ResponseEntity.ok(result); } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
MyCenterService:
//com.tanhua.sso.service.MyCenterService public Boolean checkVerificationCode(String code, String token) { //check token User user = this.userService.queryUserByToken(token); if(ObjectUtil.isEmpty(user)){ return false; } //Verify the verification code, first query the verification code in redis String redisKey = "CHECK_CODE_" + user.getMobile(); String value = this.redisTemplate.opsForValue().get(redisKey); if(StrUtil.equals(code, value)){ //delete verification code this.redisTemplate.delete(redisKey); return true; } return false; }
3.10.3. Save the new phone number
MyCenterController:
//com.tanhua.sso.controller.MyCenterController /** * Save new phone number * * @return */ @PostMapping("phone") public ResponseEntity<Void> updatePhone(@RequestBody Map<String, String> param, @RequestHeader("Authorization") String token) { try { String newPhone = param.get("phone"); boolean bool = this.myCenterService.updatePhone(token, newPhone); if (bool) { return ResponseEntity.ok(null); } } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
MyCenterService:
//com.tanhua.sso.service.MyCenterService public Boolean updatePhone(String token, String newPhone) { //check token User user = this.userService.queryUserByToken(token); if(ObjectUtil.isEmpty(user)){ return false; } Boolean result = this.userService.updatePhone(user.getId(), newPhone); if(result){ String redisKey = "TANHUA_USER_MOBILE_" + user.getId(); this.redisTemplate.delete(redisKey); } return result; }
UserService:
//com.tanhua.sso.service.UserService public Boolean updatePhone(Long userId, String newPhone) { //First check whether the new mobile phone number has been registered, if it has been registered, it cannot be modified QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("mobile", newPhone); User user = this.userMapper.selectOne(queryWrapper); if(ObjectUtil.isNotEmpty(user)){ //The new phone number has been registered return false; } user = new User(); user.setId(userId); user.setMobile(newPhone); return this.userMapper.updateById(user) > 0; }