<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>javax.annotationgroupId>
<artifactId>javax.annotation-apiartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>javax.ws.rsgroupId>
<artifactId>javax.ws.rs-apiartifactId>
<version>2.0version>
dependency>
<dependency>
<groupId>org.codehaus.jacksongroupId>
<artifactId>jackson-mapper-aslartifactId>
<version>1.9.12version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>dubboartifactId>
<version>2.8.4version>
dependency>
<dependency>
<groupId>cn.tarenagroupId>
<artifactId>1509-jt-commonartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
dependencies>
3.添加对jt-common工程的依赖
4.完善工程结构,建立pojo包和sevice包如下图:
5.建立Cart(购物车)类和DubboCartRestService接口
注意:对象要被可序列化
代码示例:
@Table(name="tb_cart")
public class Cart extends BasePojo{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private Long userId;
private Long itemId;
private String itemTitle;
private String itemImage;
private Long itemPrice;
private Integer num;
}
6.创建购物车的web工程
7.添加父工程以及对dubbo工程的依赖
此外注意:引入dubbo组件后,会导致maven的tomcat启动失败,所以,还需要再pom.xml里引入servlet的依赖:
javax.servlet:
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
8.在pom.xml文件里添加tomcat插件,并配置端口
9.引入相关的配置文件
注意:重点修改applicationContext-provider.xml里的连接参数
10.引入购物车工程的web.xml(整合dubbo的启动)
11.建立CartMapper接口类
代码示例:
public interface CartMapper extends SysMapper{
}
12.建立dubbo 的服务实现类
代码示例:
public class DubboCartRestServiceImpl implements DubboCartRestService{
@Autowired
private CartMapper cartMapper;
}
最后的结构如下:
12.完善前台工程 (jt-web)
添加对jt-dubbo工程的依赖
13.引入appliactionContext-consumer的配置文件
注意修改zookeeper的连接参数
14.建立CartController类
代码示例:
@Controller
@RequestMapping
public class CartController {
@Autowired
private DubboCartRestService dubboCartRestService;
}
15.启动dubbo环境,zookeeper环境,并对dubbo工程install后,启动前台和购物车工程测试整合是否成功
所在工程:jt-web
CartController类代码:
@Autowired
private DubboCartRestService dcrs;
@RequestMapping("/cart/show")
public String myCartList(Model model){
Long userId = 7L;
List<Cart> cartList = dcrs.myCartList(userId);
model.addAttribute("cartList", cartList);
return "cart";
}
所在工程:jt-dubbo
DubboCartRestService接口代码:
//给dubbo调用时注入,配置
@Path("cart")//http://cart.jt.com/cart/query/7
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public interface DubboCartRestService {
@GET
@Path("query")
public List<Cart> myCartList(@QueryParam(value="userId")Long userId);
}
所在工程:jt-cart
DubboCartRestServiceImpl实现类代码:
public class DubboCartRestServiceImpl implements DubboCartRestService{
@Autowired
private CartMapper cartMapper;
public List<Cart> myCartList(Long userId) {
Cart cart=new Cart();
cart.setUserId(userId);
List<Cart> cartList = cartMapper.select(cart);
return cartList;
}
所在工程:jt-web
CartController类代码:
@Controller
public class CartController {
@Autowired
private DubboCartRestService dcrs;
@RequestMapping("/cart/show")
public String myCartList(Model model){
Long userId = 7L;
List<Cart> cartList = dcrs.myCartList(userId);
model.addAttribute("cartList", cartList);
return "cart";
}
@RequestMapping("/cart/add/{itemId}")
public String addCart(@PathVariable Long itemId, Integer num,
String itemTitle,String itemImage,Long itemPrice){
Long userId = 7L;
dcrs.addAndSave(userId,itemId,num,itemTitle,itemImage,itemPrice);
return "redirect:/cart/show.html";
}
}
所在工程:jt-dubbo
DubboCartRestService接口代码:
//给dubbo调用时注入,配置
@Path("cart")//http://cart.jt.com/cart/query/7
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public interface DubboCartRestService {
@GET
@Path("query")
public List<Cart> myCartList(@QueryParam(value="userId")Long userId);
@POST
@Path("save")
public void addAndSave(@QueryParam(value="userId")Long userId,
@QueryParam(value="itemId")Long itemId,
@QueryParam(value="num")Integer num,
@QueryParam(value="itemTitle")String itemTitle,
@QueryParam(value="itemImage")String itemImage,
@QueryParam(value="itemPrice")Long price);
}
所在工程:jt-cart
DubboCartRestServiceImpl实现类代码:
public class DubboCartRestServiceImpl implements DubboCartRestService{
@Autowired
private CartMapper cartMapper;
public List<Cart> myCartList(Long userId) {
Cart cart=new Cart();
cart.setUserId(userId);
List<Cart> cartList = cartMapper.select(cart);
return cartList;
}
@Override
public void addAndSave(Long userId, Long itemId, Integer num,String itemTitle,String itemImage,Long itemPrice) {
Cart cart=new Cart();
cart.setUserId(userId);
cart.setItemId(itemId);
//判断当前用户的购物车里是否有相同商品,如果有,则进行商品数量的累加
//int count=cartMapper.checkExist(cart);
int count=cartMapper.selectCount(cart);
if(count==1){
Cart db_cart=cartMapper.select(cart).get(0);
//商品数量累加
db_cart.setNum(db_cart.getNum()+num);
db_cart.setUpdated(new Date());
//修改完后,再存进数据库
cartMapper.updateByPrimaryKeySelective(db_cart);
}else{
//如果是新添加的商品,则需要根据商品id,
//查询出商品的标题,价格,和商品的第一张图片插入到购物车里
cart.setItemTitle(itemTitle);
cart.setItemImage(itemImage);
cart.setNum(num);
cart.setItemPrice(itemPrice);
cart.setCreated(new Date());
cart.setUpdated(cart.getCreated());
cartMapper.insert(cart);
}
}
}
所在工程:jt-web
CartController类代码:
@Controller
public class CartController {
@Autowired
private DubboCartRestService dcrs;
@RequestMapping("/cart/show")
public String myCartList(Model model){
Long userId = 7L;
List<Cart> cartList = dcrs.myCartList(userId);
model.addAttribute("cartList", cartList);
return "cart";
}
@RequestMapping("/cart/add/{itemId}")
public String addCart(@PathVariable Long itemId, Integer num,
String itemTitle,String itemImage,Long itemPrice){
Long userId = 7L;
dcrs.addAndSave(userId,itemId,num,itemTitle,itemImage,itemPrice);
return "redirect:/cart/show.html";
}
@RequestMapping("/cart/update/num/{itemId}/{num}")
public String updateNum(@PathVariable Long itemId,@PathVariable Integer num){
Long userId = 7L;
dcrs.updateNum(userId,itemId,num);
return "redirect:/cart/show.html";
}
}
所在工程:jt-dubbo
DubboCartRestService接口代码:
//给dubbo调用时注入,配置
@Path("cart")//http://cart.jt.com/cart/query/7
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public interface DubboCartRestService {
@GET
@Path("query")
public List<Cart> myCartList(@QueryParam(value="userId")Long userId);
@POST
@Path("save")
public void addAndSave(@QueryParam(value="userId")Long userId,
@QueryParam(value="itemId")Long itemId,
@QueryParam(value="num")Integer num,
@QueryParam(value="itemTitle")String itemTitle,
@QueryParam(value="itemImage")String itemImage,
@QueryParam(value="itemPrice")Long price);
@GET
@Path("update/num")
public void updateNum(
@QueryParam(value="userId")Long userId,
@QueryParam(value="itemId")Long itemId,
@QueryParam(value="num")Integer num);
}
所在工程:jt-cart
DubboCartRestServiceImpl实现类代码:
public class DubboCartRestServiceImpl implements DubboCartRestService{
@Autowired
private CartMapper cartMapper;
public List<Cart> myCartList(Long userId) {
Cart cart=new Cart();
cart.setUserId(userId);
List<Cart> cartList = cartMapper.select(cart);
return cartList;
}
@Override
public void addAndSave(Long userId, Long itemId, Integer num,String itemTitle,String itemImage,Long itemPrice) {
Cart cart=new Cart();
cart.setUserId(userId);
cart.setItemId(itemId);
//判断当前用户的购物车里是否有相同商品,如果有,则进行商品数量的累加
//int count=cartMapper.checkExist(cart);
int count=cartMapper.selectCount(cart);
if(count==1){
Cart db_cart=cartMapper.select(cart).get(0);
//商品数量累加
db_cart.setNum(db_cart.getNum()+num);
db_cart.setUpdated(new Date());
//修改完后,再存进数据库
cartMapper.updateByPrimaryKeySelective(db_cart);
}else{
//如果是新添加的商品,则需要根据商品id,
//查询出商品的标题,价格,和商品的第一张图片插入到购物车里
cart.setItemTitle(itemTitle);
cart.setItemImage(itemImage);
cart.setNum(num);
cart.setItemPrice(itemPrice);
cart.setCreated(new Date());
cart.setUpdated(cart.getCreated());
cartMapper.insert(cart);
}
}
@Override
public void updateNum(Long userId, Long itemId, Integer num) {
//自定义方法,根据用户id和商品id来修改购物车商品数量
Cart cart=new Cart();
cart.setUserId(userId);
cart.setItemId(itemId);
cart.setNum(num);
cart.setUpdated(new Date());
cartMapper.updateCart(cart);
}
}
CartMapper.xml代码:
<select id="updateCart" parameterType="Cart">
update tb_cart set num=#{num},updated=#{updated} where user_id=#{userId} and item_id=#{itemId}
select>
所在工程:jt-web
CartController类代码:
@Controller
public class CartController {
@Autowired
private DubboCartRestService dcrs;
@RequestMapping("/cart/show")
public String myCartList(Model model){
Long userId = 7L;
List<Cart> cartList = dcrs.myCartList(userId);
model.addAttribute("cartList", cartList);
return "cart";
}
@RequestMapping("/cart/add/{itemId}")
public String addCart(@PathVariable Long itemId, Integer num,
String itemTitle,String itemImage,Long itemPrice){
Long userId = 7L;
dcrs.addAndSave(userId,itemId,num,itemTitle,itemImage,itemPrice);
return "redirect:/cart/show.html";
}
@RequestMapping("/cart/update/num/{itemId}/{num}")
public String updateNum(@PathVariable Long itemId,@PathVariable Integer num){
Long userId = 7L;
dcrs.updateNum(userId,itemId,num);
return "redirect:/cart/show.html";
}
@RequestMapping("/cart/delete/{itemId}")
public String delete(@PathVariable Long itemId){
Long userId=7L;
dcrs.delete(userId,itemId);
return "forward:/cart/show.html";
}
}
所在工程:jt-dubbo
DubboCartRestService接口代码:
//给dubbo调用时注入,配置
@Path("cart")//http://cart.jt.com/cart/query/7
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public interface DubboCartRestService {
@GET
@Path("query")
public List<Cart> myCartList(@QueryParam(value="userId")Long userId);
@POST
@Path("save")
public void addAndSave(@QueryParam(value="userId")Long userId,
@QueryParam(value="itemId")Long itemId,
@QueryParam(value="num")Integer num,
@QueryParam(value="itemTitle")String itemTitle,
@QueryParam(value="itemImage")String itemImage,
@QueryParam(value="itemPrice")Long price);
@GET
@Path("update/num")
public void updateNum(
@QueryParam(value="userId")Long userId,
@QueryParam(value="itemId")Long itemId,
@QueryParam(value="num")Integer num);
@GET
@Path("delete")
public void delete(
@QueryParam(value="userId") Long userId,
@QueryParam(value="itemId") Long itemId);
}
所在工程:jt-cart
DubboCartRestServiceImpl实现类代码:
public class DubboCartRestServiceImpl implements DubboCartRestService{
@Autowired
private CartMapper cartMapper;
public List<Cart> myCartList(Long userId) {
Cart cart=new Cart();
cart.setUserId(userId);
List<Cart> cartList = cartMapper.select(cart);
return cartList;
}
@Override
public void addAndSave(Long userId, Long itemId, Integer num,String itemTitle,String itemImage,Long itemPrice) {
Cart cart=new Cart();
cart.setUserId(userId);
cart.setItemId(itemId);
//判断当前用户的购物车里是否有相同商品,如果有,则进行商品数量的累加
//int count=cartMapper.checkExist(cart);
int count=cartMapper.selectCount(cart);
if(count==1){
Cart db_cart=cartMapper.select(cart).get(0);
//商品数量累加
db_cart.setNum(db_cart.getNum()+num);
db_cart.setUpdated(new Date());
//修改完后,再存进数据库
cartMapper.updateByPrimaryKeySelective(db_cart);
}else{
//如果是新添加的商品,则需要根据商品id,
//查询出商品的标题,价格,和商品的第一张图片插入到购物车里
cart.setItemTitle(itemTitle);
cart.setItemImage(itemImage);
cart.setNum(num);
cart.setItemPrice(itemPrice);
cart.setCreated(new Date());
cart.setUpdated(cart.getCreated());
cartMapper.insert(cart);
}
}
@Override
public void updateNum(Long userId, Long itemId, Integer num) {
//自定义方法,根据用户id和商品id来修改购物车商品数量
Cart cart=new Cart();
cart.setUserId(userId);
cart.setItemId(itemId);
cart.setNum(num);
cart.setUpdated(new Date());
cartMapper.updateCart(cart);
}
@Override
public void delete(Long userId, Long itemId) {
//根据用户id和商品id删除购物车里的商品
Cart cart=new Cart();
cart.setUserId(userId);
cart.setItemId(itemId);
cartMapper.delete(cart);
}
}
CartMapper.xml代码:
<select id="updateCart" parameterType="Cart">
update tb_cart set num=#{num},updated=#{updated} where user_id=#{userId} and item_id=#{itemId}
select>
所在工程:jt-web工程
OrderController类代码:
@Controller
public class OrderController {
@Autowired
private DubboOrderRestService dubboOrderRestService;
@Autowired
private DubboCartRestService dubboCartRestService;
private static final ObjectMapper MAPPER=new ObjectMapper();
//转向订单结算页面,页面要求通过Model将List传回页面,属性名是carts
@RequestMapping("/order/create")
public String create(Model model){
Long userId=7L;
List<Cart> cartList=dubboCartRestService.myCartList(userId);
model.addAttribute("carts",cartList);
return "order-cart";
}
//提交订单,页面要求返回SysResult.Ok(生成的OrderId)返回
//此外,前台会发起 /order/success 转向成功页面,并且将OrderId传给Controller
@RequestMapping("/order/submit")
@ResponseBody
public SysResult submit(Order order){
Long userId=7L;
order.setUserId(userId);
try {
String jsonOrder=MAPPER.writeValueAsString(order);
String orderId=dubboOrderRestService.saveOrder(jsonOrder);
return SysResult.oK(orderId);
} catch (Exception e) {
e.printStackTrace();
return SysResult.build(201, "订单生成失败");
}
}
//转向订单成功页面,我们要根据OrderId查询Order对象,并通过Model返回给前台
@RequestMapping("/order/success")
public String goSuccess(String id,Model model){
Order order=dubboOrderRestService.queryByOrderId(id);
model.addAttribute("order",order);
return "success";
}
}
所在工程:jt-dubbo工程
DubboOrderRestService 接口类代码:
@Path("order")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public interface DubboOrderRestService {
//按orderId查询
@GET
@Path("query")
public Order queryByOrderId(@QueryParam(value="orderId")String orderId);
//下订单
@POST
@Path("create")
public void saveOrder(@QueryParam(value="jsonOrder")String jsonOrder);
}
所在工程:jt-order工程
DubboOrderRestServiceImpl类代码:
public class DubboOrderRestServiceImpl implements DubboOrderRestService{
@Autowired
private OrderMapper orderMapper;
private static final ObjectMapper MAPPER=new ObjectMapper();
@Override
public Order queryByOrderId(String orderId) {
return orderMapper.queryByOrderId(orderId);
}
@Override
public String saveOrder(String jsonOrder) {
try {
Order order=MAPPER.readValue(jsonOrder, Order.class);
String orderId=order.getUserId()+""+System.currentTimeMillis();
order.setCreated(new Date());
order.setOrderId(orderId);
order.setUpdated(order.getCreated());
orderMapper.orderAdd(order);
return orderId;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
OrderMapper接口类代码:
public interface OrderMapper{
public Order queryByOrderId(String orderId);
public void orderAdd(Order order);
}
OrderMapper.xml代码:
<mapper namespace="com.jt.order.mapper.OrderMapper">
<resultMap type="Order" id="orderRM" autoMapping="true">
<id property="orderId" column="order_id"/>
<association property="orderShipping" select="queryOrderShipping" javaType="OrderShipping" column="order_id">
association>
<collection property="orderItems" select="queryOrderItem" javaType="ArrayList" ofType="OrderItem" column="order_id">
collection>
resultMap>
<select id="queryByOrderId" parameterType="string" resultMap="orderRM">
select * from tb_order where order_id=#{orderId}
select>
<select id="queryOrderShipping" parameterType="string">
SELECT * FROM tb_order_shipping WHERE order_id=#{orderId}
select>
<select id="queryOrderItem" parameterType="string">
SELECT * FROM tb_order_item WHERE order_id=#{orderId}
select>
<insert id="orderAdd">
INSERT INTO tb_order VALUES (#{orderId},#{payment},#{paymentType},#{postFee},#{status},#{created},#{updated},#{paymentTime},#{consignTime},#{endTime},#{closeTime},#{shippingName},#{shippingCode},#{userId},#{buyerMessage},#{buyerNick},#{buyerRate});
INSERT INTO tb_order_item VALUES
<foreach collection="orderItems" item="item" separator=",">
(#{item.itemId},#{orderId},#{item.num},#{item.title},#{item.price},#{item.totalFee},#{item.picPath})
foreach>
;
INSERT INTO tb_order_shipping VALUES (#{orderId},#{orderShipping.receiverName},#{orderShipping.receiverPhone},#{orderShipping.receiverMobile},#{orderShipping.receiverState},#{orderShipping.receiverCity},#{orderShipping.receiverDistrict},#{orderShipping.receiverAddress},#{orderShipping.receiverZip},NOW(),NOW());
insert>
mapper>
上一篇 50.大数据之旅——java分布式项目11-Dubbo