SpringCloud分布式事务实战(七)在微服务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
启动浏览器
SpringCloud分布式事务实战(七)在微服务1中创建整合函数,调用微服务2

预测结果:forum1 block 表增加 jwg10,111
Forum2 theme表增加jwg11 111

猜你喜欢

转载自blog.51cto.com/14048134/2312464
今日推荐