beancloud矿池
㈠ springcloud 能做rpc调用么
在 spring cloud 的老版本中(比如 Angel.SR3), 是自动添加了RestTemplate这个Bean,只要在相应的类中自动装配 RestTemplate 这个 Bean:
@Autowired
RestTemplate restTemplate;1212
就可以直接使用getForObject方法进行RPC:
restTemplate.getForObject(String url, Class<String> responseType, Object... uriVariables))11
2,而在比较新的版本中(比如 Camden.SR7), 是没有自动添加RestTemplate这个Bean的,需要手动添加(大坑1);并且还需要加上注解@LoadBalanced(超级大坑2,这里说超级大坑是因为没有资料提到这个注解, 在这里纠结了很久,解决的时候还是很开心的呢);
@LoadBalanced
@Bean
public RestTemplate rest() {
return new RestTemplate();
}
㈡ spring 中怎么取得bean
总共有6种方法可以实现:
方法一:在初始化时保存ApplicationContext对象
方法二:通过Spring提供的utils类获取ApplicationContext对象
方法三:继承自抽象类ApplicationObjectSupport
方法四:继承自抽象类WebApplicationObjectSupport
方法五:通过Spring提供的ContextLoader
获取spring中bean的方式总结:
方法一:在初始化时保存ApplicationContext对象
ApplicationContext ac = new ("applicationContext.xml"); ac.getBean("userService");//比如:<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>
说明:这样的方式适用于采用Spring框架的独立应用程序,须要程序通过配置文件手工初始化Spring的情况。
方法二:通过Spring提供的工具类获取ApplicationContext对象
ApplicationContext ac1 = WebApplicationContextUtils.(ServletContext sc); ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); ac1.getBean("beanId"); ac2.getBean("beanId");
说明:这样的方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。上面两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。
方法三:继承自抽象类ApplicationObjectSupport
说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法。能够方便的获取ApplicationContext。
Spring初始化时。会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。
方法四:继承自抽象类WebApplicationObjectSupport
说明:类似上面方法。调用getWebApplicationContext()获取WebApplicationContext
方法五:通过Spring提供的ContextLoader
WebApplicationContext wac = ContextLoader.();wac.getBean(beanID);
㈢ springcloud 能做rpc调用么
://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id=""
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="${userpoints.api.serviceUrl}" />
<property name="serviceInterface"
value="${userpoints.api.interface.service}" />
<property name="httpInvokerRequestExecutor">
<ref bean="httpInvokerRequestExecutor" />
</property>