SpringCloud-Eureka服务发现(3)

服务发现就是 让消费者能够访问。就是对于注册eureka里面的为服务 ,可以通过服务发现来获得该服务信息

案列:
首先在 提供者的8083里的controller添加 服务发现接口

注意 private DiscoveryClient client; 不要倒错包

package com.xxx.controller;

import java.util.List;

import org.bouncycastle.jcajce.provider.asymmetric.dsa.DSASigner.detDSA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.xxx.service.UserService;
import com.xxx.user.User;


@Controller
public class UserController {

	@Autowired
	private UserService  userService;
	
	@Autowired
	private DiscoveryClient client;     
	

	
	@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
	@ResponseBody
	
	public Object discovery()
	{
		List<String> list = client.getServices();
		System.out.println("**********" + list);

		List<ServiceInstance> srvList = client.getInstances("MICROSERVICECLOUD-DEPT");
		for (ServiceInstance element : srvList) {
			System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
					+ element.getUri());
		}
		return this.client;
	}
}

2)在启动类上 添加上
@EnableDiscoveryClient //服务发现
在这里插入图片描述

现在这个8083工程就可以自己调用自己的服务了
首先 启动 7001的注册和8083
访问
8083 加上dept/discovery 就可以访问到 了
在这里插入图片描述
回到 控制台 也打印出了 信息
在这里插入图片描述
下 一步就是 消费者 (8084)调用 提供者(8083) 的 服务了

就是把刚的代码 放到 8084 消费者里面

@RequestMapping(value = "/tt/dept/discovery")
	@ResponseBody
		public Object discovery()
		{
			return restTemplate.getForObject(REST_URL_PREFIX + "/dept/discovery", Object.class);
		}

下一步 就是把上个 3个项目 都启动了 7001(注册)8083(提供)8084(消费者)这三个项目启动
这样消费者 也能看的到 这个服务了
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

  T

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值