十次方后端笔记七:交友微服务与注册中心
完成交友微服务以及使用 Spring Cloud Eureka 搭建微服务注册中心

微服注册中心

使用Spring Cloud Eureka作为微服务注册中心。

注册中心微服务创建Module(省略)

引入依赖

  1. tensquare_parent中加入Spring Cloud版本绑定

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <dependencyManagement>
    <dependencies>
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>Finchley.M9</version>
    <type>pom</type>
    <scope>import</scope>
    </dependency>
    </dependencies>
    </dependencyManagement>
  2. tensquare_eureka中引入eureka依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
    <artifactId>tensquare_parent</artifactId>
    <groupId>com.tensquare</groupId>
    <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>tensquare_eureka</artifactId>

    <dependencies>
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    </dependencies>

    </project>

application.yml

1
2
3
4
5
6
7
8
9
10
11
server:
port: 6868 #服务端口
eureka:
client:
registerWithEureka: false #是否将自己注册到Eureka服务中,本身就是所有无需注册
fetchRegistry: false #是否从Eureka中获取注册信息
serviceUrl: #Eureka客户端与Eureka服务端进行交互的地址
defaultZone: http://127.0.0.1:${server.port}/eureka/
spring:
application:
name: tensquare_eureka

启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.tensquare.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}

交友微服务

交友微服务创建Module(省略)

表结构分析

交友微服务的表主要为:好友表和非好友表,其中非好友表类似与黑名单。

tb_friend 好友表

字段名称 字段含义 字段类型 备注
userid 用户ID 文本
friendid 好友ID 文本
islike 是否互相喜欢 文本 0:单向喜欢 1:互相喜欢

tb_nofriend 非好友表

字段名称 字段含义 字段类型 备注
userid 用户ID 文本
friendid 好友ID 文本

需求分析

  1. 当用户登陆后在推荐好友列表中点击“心”,表示喜欢此人 ,在数据库tb_friend表中插入一条数据,islike 为0

  2. 当你点击了喜欢过的人,也喜欢了你 , 表示互粉成功!也向tb_friend表中插入一条数据,islike为1 ,并且将你喜欢她的数据islike也修改为1

  3. 当你点击了不喜欢某人(点击了叉),向tb_nofriend添加记录
  4. 当两个人互粉后,其中一人不喜欢对方了,删除好友表中的记录 ,向非好友表中添加记录
  5. 用户点击了喜欢,更新用户表中的:fanscount 表示粉丝数 ,followcount表示关注数
  6. 用户删除了好友,更新用户表中的:fanscount 表示粉丝数 ,followcount表示关注数

准备工作

引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tensquare_parent</artifactId>
<groupId>com.tensquare</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>tensquare_friend</artifactId>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.tensquare</groupId>
<artifactId>tensquare_common</artifactId>
<version>${tensquare.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>

</project>

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server:
port: 9010
spring:
application:
name: tensquare-friend
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.136.104:3306/tensquare_friend?characterEncoding=utf‐8
username: root
password: 123456
jpa:
database: mysql
show-sql: true
jwt:
config:
key: imxushuai
eureka:
client:
service-url:
defaultZone: http://localhost:6868/eureka
instance:
prefer-ip-address: true

启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.tensquare.friend;

import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import util.IdWorker;
import util.JwtUtil;

@SpringCloudApplication
@EnableFeignClients
public class FriendApplication {
public static void main(String[] args) {
SpringApplication.run(FriendApplication.class, args);
}

@Bean
public IdWorker idWorker(){
return new IdWorker(1, 10);
}

@Bean
public JwtUtil jwtUtil(){
return new JwtUtil();
}
}

实体类

  1. 好友实体类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package com.tensquare.friend.pojo;

    import lombok.Data;

    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.IdClass;
    import javax.persistence.Table;
    import java.io.Serializable;

    @Data
    @Entity
    @Table(name="tb_friend")
    @IdClass(Friend.class)
    public class Friend implements Serializable {
    @Id
    private String userid;
    @Id
    private String friendid;
    private String islike;
    }
  2. 非好友实体类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    package com.tensquare.friend.pojo;

    import lombok.Data;

    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.IdClass;
    import javax.persistence.Table;
    import java.io.Serializable;

    @Data
    @Entity
    @Table(name="tb_nofriend")
    @IdClass(NoFriend.class)
    public class NoFriend implements Serializable {
    @Id
    private String userid;
    @Id
    private String friendid;
    }

添加、删除好友

添加好友与非好友

  1. FriendController

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    package com.tensquare.friend.controller;

    import com.tensquare.friend.service.FriendService;
    import entity.Result;
    import entity.StatusCode;
    import io.jsonwebtoken.Claims;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;

    import javax.servlet.http.HttpServletRequest;

    @RestController
    @RequestMapping("friend")
    public class FriendController {

    @Autowired
    private FriendService friendService;


    /**
    * 添加好友
    */
    @RequestMapping(value = "/like/{friendid}/{type}", method = RequestMethod.PUT)
    public Result addFriend(@PathVariable String friendid,
    @PathVariable String type,
    HttpServletRequest request) {
    Claims claims = (Claims) request.getAttribute("user_claims");
    if (claims == null) {
    return new Result(false, StatusCode.ACCESSERROR, "无权访问");
    }
    //如果是喜欢
    if (type.equals("1")) {
    if (friendService.addFriend(claims.getId(), friendid) == 0) {
    return new Result(false, StatusCode.REPERROR, "已经添加此好友");
    }
    } else {
    //不喜欢
    friendService.addNoFriend(claims.getId(),friendid);
    }
    return new Result(true, StatusCode.OK, "操作成功");
    }

    }
  2. FriendService

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    package com.tensquare.friend.service;

    import com.tensquare.friend.dao.FriendDao;
    import com.tensquare.friend.dao.NoFriendDao;
    import com.tensquare.friend.pojo.Friend;
    import com.tensquare.friend.pojo.NoFriend;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import javax.transaction.Transactional;

    @Service
    public class FriendService {

    @Autowired
    private FriendDao friendDao;

    @Autowired
    private NoFriendDao noFriendDao;

    @Transactional
    public int addFriend(String userid, String friendid) {
    //判断如果用户已经添加了这个好友,则不进行任何操作,返回0
    if (friendDao.selectCount(userid, friendid) > 0) {
    return 0;
    }
    //向喜欢表中添加记录
    Friend friend = new Friend();
    friend.setUserid(userid);
    friend.setFriendid(friendid);
    friend.setIslike("0");
    friendDao.save(friend);
    //判断对方是否喜欢你,如果喜欢,将islike设置为1
    if (friendDao.selectCount(friendid, userid) > 0) {
    friendDao.updateLike(userid, friendid, "1");
    friendDao.updateLike(friendid, userid, "1");
    }
    return 1;
    }


    /**
    * 向不喜欢列表中添加记录
    * @param userid
    * @param friendid
    */
    public void addNoFriend(String userid,String friendid){
    NoFriend noFriend=new NoFriend();
    noFriend.setUserid(userid);
    noFriend.setFriendid(friendid);
    noFriendDao.save(noFriend);
    }
    }
  3. FriendDao

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    package com.tensquare.friend.dao;

    import com.tensquare.friend.pojo.Friend;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.data.jpa.repository.Query;

    public interface FriendDao extends JpaRepository<Friend, String> {

    @Query("select count(f) from Friend f where f.userid=?1 and f.friendid=?2")
    int selectCount(String userid, String friendid);

    @Modifying
    @Query("update Friend f set f.islike=?3 where f.userid=?1 and f.friendid=?2")
    void updateLike(String userid, String friendid, String islike);
    }
  4. NoFriendDao

    1
    2
    3
    4
    5
    6
    7
    package com.tensquare.friend.dao;

    import com.tensquare.friend.pojo.NoFriend;
    import org.springframework.data.jpa.repository.JpaRepository;

    public interface NoFriendDao extends JpaRepository<NoFriend, String> {
    }

删除好友

  1. FriendController新增方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /**
    * 删除好友
    */
    @RequestMapping(value = "/{friendid}", method = RequestMethod.DELETE)
    public Result remove(@PathVariable String friendid,
    HttpServletRequest request) {
    Claims claims = (Claims) request.getAttribute("user_claims");
    if (claims == null) {
    return new Result(false, StatusCode.ACCESSERROR, "无权访问");
    }
    friendService.deleteFriend(claims.getId(), friendid);
    return new Result(true, StatusCode.OK, "删除成功");
    }
  2. FriendService新增方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /**
    * 删除好友
    *
    * @param userid
    * @param friendid
    */
    @Transactional
    public void deleteFriend(String userid, String friendid) {
    friendDao.deleteFriend(userid, friendid);
    friendDao.updateLike(friendid, userid, "0");
    addNoFriend(userid, friendid);//向不喜欢表中添加记录
    }
  3. FriendDao新增方法

    1
    2
    3
    @Modifying
    @Query("delete from Friend f where f.userid=?1 and f.friendid=?2")
    void deleteFriend(String userid, String friendid);

用户微服务-更新粉丝数和关注数

编写业务逻辑

变更粉丝数

  1. UserController新增方法

    1
    2
    3
    4
    5
    6
    7
    /**
    * 增加粉丝数
    */
    @RequestMapping(value = "/incfans/{userid}/{x}", method = RequestMethod.POST)
    public void incFanscount(@PathVariable String userid, @PathVariable int x) {
    userService.incFanscount(userid, x);
    }
  2. UserService新增方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    /**
    * 更新粉丝数
    *
    * @param x
    */
    @Transactional
    public void incFanscount(String userid, int x) {
    userDao.incFanscount(userid, x);
    }
  3. UserDao新增方法

    1
    2
    3
    @Modifying
    @Query("update User u set u.fanscount=u.fanscount+?2 where u.id=?1")
    void incFanscount(String userid, int x);

变更关注数

  1. UserController新增方法

    1
    2
    3
    4
    5
    6
    7
    8
    /**
    * 增加关注数
    */
    @RequestMapping(value = "/incfollow/{userid}/{x}", method =
    RequestMethod.POST)
    public void incFollowcount(@PathVariable String userid, @PathVariable int x) {
    userService.incFollowcount(userid, x);
    }
  2. UserService新增方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    /**
    * 更新关注数
    *
    * @param x
    */
    @Transactional
    public void incFollowcount(String userid, int x) {
    userDao.incFollowcount(userid, x);
    }
  3. UserDao新增方法

    1
    2
    3
    @Modifying
    @Query("update User u set u.followcount=u.followcount+?2 where u.id=?1")
    void incFollowcount(String userid, int x);

提供FeignClient

编写UserFeignClient

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.tensquare.friend.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient("tensquare_user")
public interface UserClient {
/**
* 增加粉丝数
*
* @param userid
* @param x
*/
@RequestMapping(value = "/user/incfans/{userid}/{x}", method =
RequestMethod.POST)
void incFanscount(@PathVariable("userid") String userid, @PathVariable("x") int x);

/**
* 增加关注数
*
* @param userid
* @param x
*/
@RequestMapping(value = "/user/incfollow/{userid}/{x}", method =
RequestMethod.POST)
void incFollowcount(@PathVariable("userid") String userid, @PathVariable("x") int x);
}

修改addFriend和deleteFriend逻辑

修改FriendService相关逻辑即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
   @Autowired
private UserClient userClient;

@Transactional
public int addFriend(String userid, String friendid) {
//判断如果用户已经添加了这个好友,则不进行任何操作,返回0
if (friendDao.selectCount(userid, friendid) > 0) {
return 0;
}
//向喜欢表中添加记录
Friend friend = new Friend();
friend.setUserid(userid);
friend.setFriendid(friendid);
friend.setIslike("0");
friendDao.save(friend);

userClient.incFollowcount(userid,1);//增加自己的关注数
userClient.incFanscount(friendid,1);//增加对方的粉丝数

//判断对方是否喜欢你,如果喜欢,将islike设置为1
if (friendDao.selectCount(friendid, userid) > 0) {
friendDao.updateLike(userid, friendid, "1");
friendDao.updateLike(friendid, userid, "1");
}
return 1;
}

/**
* 删除好友
*
* @param userid
* @param friendid
*/
@Transactional
public void deleteFriend(String userid, String friendid) {
friendDao.deleteFriend(userid, friendid);
friendDao.updateLike(friendid, userid, "0");

userClient.incFollowcount(userid,-1);//增加自己的关注数
userClient.incFanscount(friendid,-1);//增加对方的粉丝数

addNoFriend(userid, friendid);//向不喜欢表中添加记录
}
文章作者: imxushuai
文章链接: https://www.imxushuai.com/2002/01/02/7.十次方后端笔记七:交友微服务与注册中心/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 imxushuai
支付宝打赏
微信打赏