微服務分佈式事務實戰(七)在微服務1中創建整合函數,調用微服務2

(1) 添加jar pom.xml

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-feign</artifactId>
            </dependency>

(2)在主程序中添加註解

@EnableFeignClients

(3)編寫調用微服務的代碼(調用服務2)
1 創建theme實體

public class Theme {
private  Integer id;
private  String  tName;
private  String  tDescription;
get  set ;
}

2 編寫訪問theme服務代碼

@FeignClient(value="themeMicroService",  //服務1

fallback=Demo2ClientHystric.class  //容錯處理類 
)

public interface ThemeClient {

    @RequestMapping(value="/getThemeList",//2接口
            method=RequestMethod.GET)

    public    List<Theme>  getThemeList();//list

    @RequestMapping(value="/saveTheme",method=RequestMethod.GET)
     public int saveTheme(
             @RequestParam("tName") String tName  ,// 3傳遞參數
             @RequestParam("tDescription")  String tDescription,
             @RequestParam("blockId")   Integer blockId
             );

}

3 編寫錯誤處理類

@Component
public class Demo2ClientHystric implements ThemeClient {
    @Override
    public List<Theme> getThemeList() {
        // TODO Auto-generated method stub
        System.out.println("進入斷路器");
        throw new RuntimeException(" 失敗.");
    }
    // 丟出異常
    @Override
    public int saveTheme(String tName, String tDescription, Integer blockId) {
        // TODO Auto-generated method stub
        System.out.println("進入斷路器");
        throw new RuntimeException("失敗.");
    }
}

(4)編寫整合服務:訪問2個服務
訪問微服務1dao ,訪問微服務2

1 接口:

public interface BlockThemeService {

    int saveBlockTheme(Block block, Theme theme);
    }

2 實現

//第三個微服務整合
@Service
public class BlockThemeServiceImpl {
    @Autowired
    private BlockDao blockDao; // 1區塊訪問dao—微服務1內容

    @Autowired
    private ThemeClient themeClient; // 2主題微服務訪問—微服務2的內容 

    @Transactional
    public int saveBlockTheme(Block block, Theme theme) {
            int rs1 = blockDao.saveBlock("jwg10", "111");// 3 保存1
        int rs2 = themeClient.saveTheme("jwg11", "111", 1);// 4 保存2
        return rs1 + rs2;
    }
}

(5)編寫控制層

發佈整合接口

@RestController
public class BlockThemeController {
    @Autowired
    private BlockThemeService blockThemeService;
    @RequestMapping("/saveBlockTheme")
    public String saveBlockTheme() {
//調用整合服務
        Integer rs = blockThemeService.saveBlockTheme(null, null);
        return rs.toString();
    }
}

(6)測試

啓動註冊中心,啓動themeMicroService ,啓動BlockMicroService
啓動瀏覽器
在這裏插入圖片描述

預測結果:forum1 block 表增加 jwg10,111
Forum2 theme表增加jwg11 111
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章