使用eureka完成分页、增删改查

maven镜像:

<mirror>
            <id>huaweicloud</id>
            <url>https://repo.huaweicloud.com/repository/maven</url>
            <mirrorOf>central</mirrorOf>
        </mirror>

eureka-server:

yml:

spring:
  application:
    name: eureka-server
eureka:
  client:
    service-url:
      defaultZone: http://localhost:5050/eureka
    register-with-eureka: false
    fetch-registry: false
server:
  port: 5050

main方法:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }

}

公共public

entity实体类

package org.example.entity;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class News implements Serializable {
    private Integer nid;

    private Integer ntid;

    private String ntitle;

    private String nauthor;

    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date ncreatedate;

    private String npicpath;

    private Date nmodifydate;

    private String nsummary;

    private String ncontent;

    private String tname;


    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }

    public Integer getNid() {
        return nid;
    }

    public void setNid(Integer nid) {
        this.nid = nid;
    }

    public Integer getNtid() {
        return ntid;
    }

    public void setNtid(Integer ntid) {
        this.ntid = ntid;
    }

    public String getNtitle() {
        return ntitle;
    }

    public void setNtitle(String ntitle) {
        this.ntitle = ntitle == null ? null : ntitle.trim();
    }

    public String getNauthor() {
        return nauthor;
    }

    public void setNauthor(String nauthor) {
        this.nauthor = nauthor == null ? null : nauthor.trim();
    }

    public Date getNcreatedate() {
        return ncreatedate;
    }

    public void setNcreatedate(Date ncreatedate) {
        this.ncreatedate = ncreatedate;
    }

    public String getNpicpath() {
        return npicpath;
    }

    public void setNpicpath(String npicpath) {
        this.npicpath = npicpath == null ? null : npicpath.trim();
    }

    public Date getNmodifydate() {
        return nmodifydate;
    }

    public void setNmodifydate(Date nmodifydate) {
        this.nmodifydate = nmodifydate;
    }

    public String getNsummary() {
        return nsummary;
    }

    public void setNsummary(String nsummary) {
        this.nsummary = nsummary == null ? null : nsummary.trim();
    }

    public String getNcontent() {
        return ncontent;
    }

    public void setNcontent(String ncontent) {
        this.ncontent = ncontent == null ? null : ncontent.trim();
    }
}

package org.example.entity;

import java.io.Serializable;

public class Topic implements Serializable {
    private Integer tid;

    private String tname;

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname == null ? null : tname.trim();
    }
}

remote接口:

public interface NewsRemote {
    @PostMapping("newsByPage")
    BizVo<PageInfo<News>> newsByPage(@RequestBody Map<String,Object> params);

    @PostMapping("newsById")
    BizVo<News> newsById(@RequestBody Map<String,Object> params);

    @PostMapping("addNews")
    BizVo<Boolean> addNews(@ModelAttribute News news,
                           @RequestParam(required = false) MultipartFile multipartFile,
                           HttpServletRequest req) throws SftpException, IOException;

    @PostMapping("updateNews")
    BizVo<Boolean> updateNews(@ModelAttribute News news,
                           @RequestParam(required = false) MultipartFile multipartFile,
                           HttpServletRequest req) throws SftpException, IOException;

    @PostMapping("deleteNews")
    BizVo<Boolean> deleteNews(@RequestBody Map<String, Object> map);

    @PostMapping("topicList")
    BizVo<List<Topic>> topicList();
}



public interface TopicRemote {
    @GetMapping("allTopic")
    BizVo<List<Topic>> allTopic();
}

工具类:

package org.example.utils;

public class BizVo<T> {
    private int code;
    private String name;
    private T payload;

    public BizVo() {
    }

    public BizVo(int code, String name, T payload) {
        this.code = code;
        this.name = name;
        this.payload = payload;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public T getPayload() {
        return payload;
    }

    public void setPayload(T payload) {
        this.payload = payload;
    }
}

news项目--消费者

YML:

server:
  port: 6061
spring:
  application:
    name: sc-news-service
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/new?characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: zc162157
  main:
    allow-circular-references: true
mybatis:
  type-aliases-package: org.example.entity
  mapper-locations: mapper/*.xml
#eureka:
#  client:
#    service-url:
#      defaultZone: http://localhost:5050/eureka
feign:
  hystrix:
    enabled: true

sc-topic-service:
  ribbon:
    # NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置规则 随机
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #配置规则 轮询
    # NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RetryRule #配置规则 重试
    # NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule #配置规则 响应时间权重
#    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #配置规则 最空闲连接策略
    ConnectTimeout: 1000 #请求连接超时时间
    ReadTimeout: 1000 #请求处理的超时时间
    OkToRetryOnAllOperations: true #对所有请求都进行重试
    MaxAutoRetriesNextServer: 1 #切换实例的重试次数
    MaxAutoRetries: 1 #对当前实例的重试次数



dao层:

@Mapper
@Repository
public interface NewsMapper {
    int deleteByPrimaryKey(Integer nid);

    int insert(News record);

    int insertSelective(News record);

    News selectByPrimaryKey(Integer nid);

    int updateByPrimaryKeySelective(News record);

    int updateByPrimaryKeyWithBLOBs(News record);

    int updateByPrimaryKey(News record);

    List<News> selectAll(Map<String,Object> params);

    News selectById(int id);
}

service层

public interface NewsService {
    PageInfo<News> newsByPage(Map<String,Object> params);

    News getNewsById(int id);

    boolean addNews(News news);

    List<Topic> getAllTopic();

    boolean updateNews(News news);

    boolean deleteNews(int id);
}

service实现类

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private TopicClient topicClient;

    @Override
    public PageInfo<News> newsByPage(Map<String, Object> params) {
        PageHelper.startPage(params);
        List<News> list = newsMapper.selectAll(params);
        List<Topic> topicList = topicClient.allTopic().getPayload();
        for(News news: list){
            if(topicList!=null){
            for(Topic topic : topicList){
                if(news.getNtid() == topic.getTid()){
                    news.setTname(topic.getTname());
                    break;
                }
            }
            }

        }
        return new PageInfo<>(list);
    }

    @Override
    public News getNewsById(int id) {
        return newsMapper.selectById(id);
    }

    @Override
    public boolean addNews(News news) {
        if(newsMapper.insertSelective(news)>0){
            return true;
        }
        return false;
    }

    @Override
    public List<Topic> getAllTopic() {
        return topicClient.allTopic().getPayload();
    }

    @Override
    public boolean updateNews(News news) {
        if(newsMapper.updateByPrimaryKeySelective(news)>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteNews(int id) {
        if(newsMapper.deleteByPrimaryKey(id)>0){
            return true;
        }
        return false;
    }


}

controller层

@RestController
public class NewsController implements NewsRemote {
    @Autowired
    private NewsService newsService;

    @Override
    public BizVo<PageInfo<News>> newsByPage(Map<String, Object> params) {
        if(params.get("ntitle").toString()!=null){
            params.put("ntitle","%"+params.get("ntitle").toString()+"%");
        }
        for (int i = 0; i < 9; i++) {
            newsService.newsByPage(params);
        }
        BizVo<PageInfo<News>> bizVo = new BizVo<>(200,"success",newsService.newsByPage(params));
        return bizVo;
    }

    @Override
    public BizVo<News> newsById(Map<String, Object> params) {
        int id = Integer.parseInt(params.get("id").toString());
        BizVo<News> bizVo = new BizVo<>(200,"success",newsService.getNewsById(id));
        return bizVo;
    }

   
    @Override
    public BizVo<Boolean> deleteNews(Map<String, Object> map) {
        int id = Integer.parseInt(map.get("id").toString());
        BizVo<Boolean> bizVo = new BizVo<>(200,"success",newsService.deleteNews(id));
        return bizVo;
    }

    @Override
    public BizVo<List<Topic>> topicList() {
        BizVo<List<Topic>> bizVo = new BizVo<>(200,"success",newsService.getAllTopic());
        return bizVo;
    }

}

远程连接:

@FeignClient(name = "sc-topic-service",fallbackFactory = TopicClientFallBack.class)
@Component
public interface TopicClient extends TopicRemote {
}

执行熔断:

@Component
public class TopicClientFallBack implements FallbackFactory<TopicRemote> {
    @Override
    public TopicRemote create(Throwable cause) {
        System.out.println("执行熔断");
        return new TopicRemote(){
            public BizVo<List<Topic>> allTopic(){
                BizVo<List<Topic>> bizVo = new BizVo<>(5500,"服务器暂不可用,稍后在试!",null);
                return bizVo;
            }
        };
    }
}

文件上传:

<tr>
            <td>图片</td>
            <td><input type="file" ref="fileName"></td>
        </tr>
 addNews: function () {
                if (this.title== '' || this.author == '' || this.content == '' || this.summary == ''||this.tid == 0) {
                    alert('请填写完整信息');
                    return;
                }
                const fileName = this.$refs.fileName;
                const file = fileName.files[0];
                if(fileName && fileName.files && fileName.files.length > 0){
                    const file = fileName.files[0];
                    this.fileUpload(file);
                }else {
                    alert("请选择图片");
                    return;
                }
            },
            fileUpload(file){
                if(!confirm("确定增加新闻?")){
                    return;
                }
                var formData = new FormData();
                formData.append('ntitle',this.title);
                formData.append('nauthor',this.author);
                formData.append('ncontent',this.content);
                formData.append('nsummary',this.summary);
                formData.append('ntid',this.tid);
                formData.append('multipartFile',file);
                axios.post("addNews",formData,{
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }}).then(rs=>{
                    if(rs.data.payload){
                        window.confirm("增加成功")
                        window.location="news.html"
                    }else{
                        window.confirm("增加失败")
                    }
                })
            },
 @Override
    public BizVo<Boolean> addNews(News news, MultipartFile multipartFile, HttpServletRequest req) throws SftpException, IOException {
        String ordfileName = null;
        String newfileName = null;
        if (multipartFile != null) {
            ordfileName = multipartFile.getOriginalFilename();
            newfileName = UUID.randomUUID().toString() + ordfileName.substring(ordfileName.lastIndexOf("."));
            String filePath = "E:/temp/";
            File file1 = new File(filePath);
            if(!file1.exists()){
                file1.mkdir();
            }
            multipartFile.transferTo(new File(filePath,newfileName));
            news.setNpicpath(newfileName);
        }
        BizVo<Boolean> bizVo = new BizVo<>(200,"success",newsService.addNews(news));
        return bizVo;
    }
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("upload/**").addResourceLocations("file:E:/temp/");
    }
}

main方法:


@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class ScNewsApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScNewsApplication.class, args);
    }

}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]: SpringCloud整合Mybatis做增删改查。引用\[2\]: 我相比之前写的结合springcloud结合mybati实现增删改查。这一次写了一个纯注解方式来实现简单的增删改查。引用\[3\]: springCloud常用的六大组件 服务发现 —— Eureka 服务调用 —— Feign 服务熔断 —— Hystrix 负载均衡 —— Ribbon 服务网关 —— Zuul 分布式配置— Config。 回答: 在SpringCloud中,可以使用Mybatis来实现增删改查操作。通过整合SpringCloud和Mybatis,我们可以使用纯注解方式来实现简单的增删改查。同时,SpringCloud还提供了一些常用的组件,如服务发现(Eureka)、服务调用(Feign)、服务熔断(Hystrix)、负载均衡(Ribbon)、服务网关(Zuul)和分布式配置(Config)等。这些组件可以帮助我们更方便地开发和管理微服务架构。 #### 引用[.reference_title] - *1* *3* [SpringCloud整合Mybatis做增删改查](https://blog.csdn.net/Gfz80k/article/details/103509825)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springcloud微服务实现增删改查](https://blog.csdn.net/FindHuni/article/details/85049506)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值