SpringCloud整合Feign

此处整合Feign,使用feign实现服务调用!这里只是配置简单使用,后续会更新服务降级内容!
1、引入依赖

<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-openfeignartifactId>
			<version>2.1.1.RELEASEversion>
		dependency>

创建feign接口:

package org.rosefinch.business.core;

import java.util.List;
import java.util.Map;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mythical.rosefinch.entity.bean.User;
//name 名称随意
//url是调用服务地址rosefinch-business 配置在host文件中
//RequestMapping 调用服务的请求方法
@FeignClient(name = "rosefinch-business", url = "http://rosefinch-business:8081")
public interface UserClient {

	/* @GetMapping("/user/getAllUser") */
	@RequestMapping("/user/getAllUser")
	public List<User> getUser(@RequestParam Map<String, Object> paramMap);
	
}

B服务方法创建

package com.mythical.rosefinch.business.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mythical.rosefinch.business.mapper.UserMapper;
import com.mythical.rosefinch.entity.bean.User;

@RestController
@RequestMapping("/user")
@Transactional
public class UserService {

	@Autowired
	private UserMapper userMapper;
	
	@RequestMapping("/getAllUser")
	public List<User> getAllUser(){
		return userMapper.getAllUser();
	}
}

A服务调用B服务
创建A服务:

package com.mythical.rosefinch.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.rosefinch.business.core.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mythical.rosefinch.entity.bean.User;

@RestController
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserClient userClient;
	
	@RequestMapping("/getAllUser")
    public List<User> getAllUser() {
		Map<String, Object> m = new HashMap<String, Object>();
        return userClient.getUser(m);
    }
}

A中启动类要注意:

//@EnableFeignClients("org.rosefinch.business.core") 此处要注意UserClient要注册到Spring容器中,否则会报错,因为我的core是一个jar包引入的所以用这样的方式注入
package com.mythical.rosefinch.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients("org.rosefinch.business.core")
public class RosefinchWebApplication {
	public static void main(String[] args) {
		SpringApplication.run(RosefinchWebApplication.class, args);
	}

}

你可能感兴趣的:(SpringCloud)