1. 程式人生 > 實用技巧 >十次方微服務專案開發實踐,交友微服務

十次方微服務專案開發實踐,交友微服務

一、需求分析

交友微服務本身的功能:
(1)當用戶登陸後在推薦好友列表中點選“心”,表示喜歡此人 ,在資料庫tb_friend表中插入一條資料,islike 為0
(2)當你點選了喜歡過的人,也喜歡了你 , 表示互粉成功!也向tb_friend表中插入一條資料,islike為1 ,並且將你喜歡她的資料islike也修改為1
(3)當你點選了不喜歡某人(點選了叉),向tb_nofriend新增記錄.
(4)當兩個人互粉後,其中一人不喜歡對方了,刪除好友表中的記錄 ,向非好友表中新增記錄
什麼場景下使用springCloud呢?
我們來看使用者表,有兩列: fanscount 表示粉絲數 ,followcount表示關注數

(1)當用戶點選了喜歡:
比如小寶關注了楚楚,小寶的followcount(關注數)加1 , 楚楚的fanscount (粉絲數)加1
(2)當用戶刪除了好友:
比如楚楚刪除了好友小寶,小寶的fanscount (粉絲數)減1 ,楚楚的followcount(關注數)減1

二、交友微服務-新增與刪除好友

1.搭建模組

(1)建立工程tensquare_friend,pom.xml引入依賴

<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>1.0-SNAPSHOT</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>
  • 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

(2)建立application.yml

server:
  port: 9010
spring:
  application:
    name: tensquare-friend #指定服務名
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.192.130:3306/tensquare_friend?characterEncoding=UTF8&&useSSL=false
    username: root
    password: 123456
  jpa:
    database: MySQL
    show-sql: true
jwt:
  config:
    key: eknaij
    ttl: 360000
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

(3)編寫啟動類

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class FriendApplication {
    public static void main(String[] args) {
        SpringApplication.run(FriendApplication.class, args);
    }
    @Bean
    public IdWorker idWorkker(){
        return new IdWorker(1, 1);
    }
    @Bean
    public JwtUtil jwtUtil(){
        return new util.JwtUtil();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

(4)建立JwtFilter(參見User工程)
(5)建立ApplicationConfig(參見User工程)

2.新增好友
(1)建立實體類

@Entity
@Table(name="tb_friend")
@IdClass(Friend.class)
public class Friend implements Serializable {
    @Id
    private String userid;
    @Id
    private String friendid;
    private String islike;
    public String getUserid() {
        return userid;
    }
    public void setUserid(String userid) {
        this.userid = userid;
    }
    public String getFriendid() {
        return friendid;
    }
    public void setFriendid(String friendid) {
        this.friendid = friendid;
    }

    public String getIslike() {
        return islike;
    }

    public void setIslike(String islike) {
        this.islike = islike;
    }
}
  • 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

(2)新建dao包,建立FriendDao介面

/**
 * 交友資料訪問層
 */
public interface FriendDao extends JpaRepository<Friend,String> {
    /**
     * 根據使用者ID與被關注使用者ID查詢記錄個數
     * @param userid
     * @param friendid
     * @return
     */
    @Query("select count(f) from Friend f where f.userid=?1 and f.friendid=?2")
    public int selectCount(String userid,String friendid);
    /**
     * 更新為互相喜歡
     * @param userid
     * @param friendid
     */
    @Modifying
    @Query("update Friend f set f.islike=?3 where f.userid=?1 and f.friendid=?2")
    public void updateLike(String userid,String friendid,String islike);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

(3)建立業務邏輯類
建立com.tensquare.friend.service包,包下建立類FriendService

@Service
public class FriendService {
    @Autowired
    private FriendDao friendDao;
    @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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

(4)控制器類
建立包com.tensquare.friend.controller,包下建立FriendController

@RestController
@RequestMapping("/friend")
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private HttpServletRequest request;
    /**
     * 新增好友
     * @param friendid 對方使用者ID
     * @param type 1:喜歡 0:不喜歡
     * @return
     */
    @RequestMapping(value="/like/{friendid}/{type}",method= RequestMethod.PUT)
    public Result addFriend(@PathVariable String friendid , @PathVariable String type){
        Claims claims=(Claims)request.getAttribute("user_claims");
        if(claims==null){
            return new Result(false, StatusCode.ACCESSERROR,"無權訪問",null);
        }
        //如果是喜歡
        if(type.equals("1")){
            if(friendService.addFriend(claims.getId(),friendid)==0){
                return new Result(false, StatusCode.REPERROR,"已經新增此好友",null);
            }
        }else{
        //不喜歡
        }
        return new Result(true, StatusCode.OK, "操作成功",null);
    }
}
  • 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

(5)測試:
啟動使用者微服務,登陸使用者獲取token
啟動交友微服務,通過postMan測試http://localhost:9010/friend/like/1/1,新增頭資訊Authorization 內容為Bearer 加上獲取的token.

三、新增非好友

需求:當用戶點選不喜歡某人,將對方的ID記錄不喜歡列表中
(1)構建實體類

@Entity
@Table(name="tb_nofriend")
@IdClass(NoFriend.class)
public class NoFriend implements Serializable {
    @Id
    private String userid;
    @Id
    private String friendid;
    public String getUserid() {
        return userid;
    }
    public void setUserid(String userid) {
        this.userid = userid;
    }
    public String getFriendid() {
        return friendid;
    }
    public void setFriendid(String friendid) {
        this.friendid = friendid;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

(2)建立資料訪問介面

/**
 * 不喜歡列表資料訪問層
 */
public interface NoFriendDao extends JpaRepository<NoFriend,String> {
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

(3)修改業務邏輯類FriendService

    @Autowired
    private NoFriendDao noFriendDao;
    /**
     * 向不喜歡列表中新增記錄
     * @param userid
     * @param friendid
     */
    public void addNoFriend(String userid,String friendid){
        NoFriend noFriend=new NoFriend();
        noFriend.setUserid(userid);
        noFriend.setFriendid(friendid);
        noFriendDao.save(noFriend);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

(2)修改FriendController的addFriend方法
在else中新增:

  friendService.addNoFriend(claims.getId(),friendid);//向不喜歡列表中新增記錄
  • 1

四、刪除好友

(1)FriendDao新增方法定義

    /**
     * 刪除喜歡
     * @param userid
     * @param friendid
     */
    @Modifying
    @Query("delete from Friend f where f.userid=?1 and f.friendid=?2")
    public void deleteFriend(String userid,String friendid);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(2)FriendService新增方法


    /**
     * 刪除好友
     * @param userid
     * @param friendid
     */
    @Transactional
    public void deleteFriend(String userid,String friendid){
        friendDao.deleteFriend(userid,friendid);
        friendDao.updateLike(friendid,userid,"0");
        addNoFriend(userid,friendid);//向不喜歡錶中新增記錄
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

(3)FriendController新增方法


    /**
     * 刪除好友
     * @param friendid
     * @return
     */
    @RequestMapping(value="/{friendid}",method=RequestMethod.DELETE)
    public Result remove(@PathVariable String friendid){
        Claims claims=(Claims)request.getAttribute("user_claims");
        if(claims==null){
            return new Result(false, StatusCode.ACCESSERROR,"無權訪問",null);
        }
        friendService.deleteFriend(claims.getId(), friendid);
        return new Result(true, StatusCode.OK, "刪除成功",null);
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

五、粉絲數與關注數的變更

1.變更粉絲數

(1)修改tensquare_user工程的UserDao,增加方法定義

    /**
     * 更新粉絲數
     * @param userid 使用者ID
     * @param x 粉絲數
     */
    @Modifying
    @Query("update User u set u.fanscount=u.fanscount+?2 where u.id=?1")
    public void incFanscount(String userid,int x);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(2)UserService增加方法

	/**
	 * 更新粉絲數
	 * @param x
	 */
	@Transactional
	public void incFanscount(String userid,int x){
		userDao.incFanscount(userid,x);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(3)UserController增加方法

	/**
	 * 增加粉絲數
	 * @param userid
	 * @param x
	 */
	@RequestMapping(value="/incfans/{userid}/{x}",method= RequestMethod.POST)
	public void incFanscount(@PathVariable String userid,@PathVariable int x){
		userService.incFanscount(userid,x);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.變更關注數

(1)修改tensquare_user工程的UserDao,增加方法定義

    /**
     * 更新關注數
     * @param userid 使用者ID
     * @param x 粉絲數
     */
    @Modifying
    @Query("update User u set u.followcount=u.followcount+?2 where u.id=?1")
    public void incFollowcount(String userid,int x);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(2)UserService增加方法

	/**
	 * 更新關注數
	 * @param x
	 */
	@Transactional
	public void incFollowcount(String userid,int x){
		userDao.incFollowcount(userid,x);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(3)UserController增加方法

	/**
	 * 增加關注數
	 * @param userid
	 * @param x
	 */
	@RequestMapping(value="/incfollow/{userid}/{x}",method= RequestMethod.POST)
	public void incFollowcount(@PathVariable String userid,@PathVariable int x){
		userService.incFollowcount(userid,x);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

六、呼叫使用者微服務

1.喜歡某人更新使用者資料

(1)在tensquare_friend模組建立 com.tensquare.friend.client包,包下建立介面

/**
 * 使用者客戶端
 */
@FeignClient("tensquare-user")
public interface UserClient {
    
    /**
     * 增加粉絲數
     * @param userid
     * @param x
     */
    @RequestMapping(value="/user/incfans/{userid}/{x}",method= RequestMethod.POST)
    public void incFanscount(@PathVariable("userid") String userid, @PathVariable("x") int x);

    /**
     * 增加關注數
     * @param userid
     * @param x
     */
    @RequestMapping(value="/user/incfollow/{userid}/{x}",method= RequestMethod.POST)
    public void incFollowcount(@PathVariable("userid") String userid,@PathVariable("x") int x);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

@FeignClient註解用於指定從哪個服務中呼叫功能
@RequestMapping註解用於對被呼叫的微服務進行地址對映。
注意 @PathVariable註解一定要指定引數名稱,否則出錯
(2)修改FriendService ,注入UserClient

@Autowired
private UserClient userClient;
  • 1
  • 2

修改addFriend方法,增加對userClient方法的呼叫

    @Autowired
    private UserClient userClient;
    ........
    ........
        //如果是喜歡
        userClient.incFollowcount(claims.getId(),1);//增加自己的關注數
        userClient.incFanscount(friendid,1);//增加對方的粉絲數
        return new Result(true, StatusCode.OK, "操作成功",null);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2.刪除好友更新使用者資料

修改FriendService的deleteFriend方法 ,增加呼叫

        userClient.incFollowcount(claims.getId(),-1);//減少自己的關注數
        userClient.incFanscount(friendid,-1);//減少對方的粉絲數