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);
}
}