微服務分散式事務實戰(七)在微服務1中建立整合函式,呼叫微服務2
阿新 • • 發佈:2018-12-19
(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