Spring Cloud AWS: optional cache manager - caching

Spring cache configuration allows to fall back to no cache using CompositeCacheManager with fallbackToNoOpCache property set to true. How could this be used with spring-cloud-aws cache manager so that, when a non-existing cache cluster is specified, the composite cache manager falls back to no cache? With an example configuration like this:
<aws-cache:cache-manager>
<aws-cache:cache-cluster name="CacheCluster" />
</aws-cache:cache-manager>
the application just won't start when there's no cluster named CacheCluster configured. When a CompositeCacheManager is configured like this:
<aws-cache:cache-manager id="elasticacheManager">
<aws-cache:cache-cluster name="CacheCluster" />
</aws-cache:cache-manager>
<bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
<property name="cacheManagers">
<list>
<ref bean="elasticacheManager" />
</list>
</property>
<property name="fallbackToNoOpCache" value="true"/>
</bean>
with a non-existing cache CacheCluster, then the application fails to start up complaining: "No bean named 'elasticacheManager' is defined".
Is there a way to create an AWS cache manager programmatically and use something like a FactoryBean for this?

Currently Spring Cloud AWS does not support the configuration of a fallback cache. I will add it to our backlog as a feature request. In the meantime you could use the same workaround I did in the reference application using spring profiles (see ReferenceApplication.java).

Related

Hazelcast with spring namespace - init the node when context is loaded

i have hazelcast instance defined using the hazelcast name space and a map in it. also using spring cache abstraction to define cacheManager.
<bean name="siteAdminPropertyPlaceHolderConfigurer"
class="org.sample.SiteAdminPropertyPlaceHolderConfigurer">
<property name="order" value="1000"/>
<!-- last one-->
</bean>
<!-- hazelcast cache manager -->
<hz:hazelcast id="instance" lazy-init="true">
<hz:config>
<hz:group name="${HAZEL_GROUP_NAME}" password="${HAZEL_GROUP_PASSWORD}"/>
<hz:network port="${HAZEL_NETWORK_PORT}" port-auto-increment="true">
<hz:join>
<hz:multicast enabled="${HAZEL_MULTICAST_ENABLED}"
multicast-group="224.2.2.3"
multicast-port="54327"/>
<hz:tcp-ip enabled="${HAZEL_TCP_ENABLED}">
<hz:members>${HAZEL_TCP_MEMBERS}</hz:members>
</hz:tcp-ip>
</hz:join>
</hz:network>
<hz:map name="oauthClientDetailsCache"
backup-count="1"
max-size="0"
eviction-percentage="30"
read-backup-data="true"
eviction-policy="NONE"
merge-policy="com.hazelcast.map.merge.PassThroughMergePolicy"/>
</hz:config>
</hz:hazelcast>
<bean id="hazelcastCacheManager" class="com.hazelcast.spring.cache.HazelcastCacheManager" lazy-init="true"
depends-on="instance">
<constructor-arg ref="instance"/>
</bean>
The problem is that ,this spring context is also used for other tools we have besides the server and that hazelcast starts listening on the port and the tool actually never exit.
i tried to disable all network join (enabled=false) and i though to enable them programatically only when the server starts. but it does not work hazelcast still starts.
i don't want to give up the spring name space as its very convenient for developers to define new maps(spring caches). also i want as little hazelcast code in there.
any idea how to achieve this ?
thanks
Shlomi
I didn't find a way to do this except telling hazecast to shutdown at the end of each tool run.
i also moved the definition above to separated XML context file so it would not be loaded by the tools (at least not all of them)
Hazelcase.shutdownAll();

Multi-tenant webapp using Spring MVC and Hibernate 4.2.0.Final

I have developed a small webapp using and SpringMVC(3.1.3.RELEASE) and Hibernate 4.2.0.Final.
I'm trying to convert it to be a multi-tenant application.
Similar topics have been covered in other threads, but I couldn't find a definitive solution to my problem.
What I am trying to achieve is to design a web app which is able to:
Read a datasource configuration at startup (an XML file containing multiple datasource definitions, which is placed outside the WAR file and it's not the application-context or hibernate configuration file)
Create a session factory for each one of them (considering that each datasource is a database with a different schema).
How can i set my session factory scope as session? ( OR Can i reuse the same session factory ?) .
Example:
Url for client a - URL: http://project.com/a/login.html
Url for client b - URL: http://project.com/b/login.html
If client "a" make request,read the datasource configuration file and Create a session factory using that XML file for the client "a".
This same process will be repeating if the client "b" will send a request.
What I am looking, how to implement datasource creation upon customer subscription without editing the Spring configuration file. It needs to be automated.
Here is my code ,that i have done so far.
Please anyone tell me,What modifications i need to be made?
Please give an answer with some example code..I am quite new in spring and hibernate world.
Spring.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
JDBC.properties File
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/Logistics
jdbc.username=root
jdbc.password=rot#pspl#12
hibernate.cfg.xml File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="pepper.logis.organizations.model.Organizaions" />
<mapping class="pepper.logis.assets.model.Assets" />
</session-factory>
</hibernate-configuration>
Thanks,
First create a table for Tenant with tenant_id and associate it with all users.Now, you can fetch this details while the user logs in and set it in session.
We are using AbstractRoutingDataSource to switch DataSource for every request on Spring Boot. I think it is Hot Swapable targets/datasource mentioned by #bhantol above.
It solves our problems but I don't think it is sound solution. I guess JNDI could be a better one than AbstractRoutingDataSource.
Wondering what you ended up with.
Here are some ideas for you.
Option 1) Single Application Instance.
It is somewhat ambitious to to this using what you are actually trying to achieve.
The gist is to simply deploy the same exact application with different context root on the same JVM. You can still tune the JVM as a whole like you would have if you had a truely multi-tenant application. But this comes at the expense of duplication of classes, contexts, local caching, start up times etc.
But as of today the Spring Framework 4.0 does not provide much of an multi-tenancy support (other than Hot Swapable targets/datasource) etc. I am looking for a good framework but it may be a wash to move away from Spring at this time for me.
Option 2) Multiple deployments of same application (more practical as of today)
Just have your same exact application deploy to the same application server JVM instance or even different.
If you use the same instance you may now need to bootstrap your app to pickup a DataSource based on what the instance should serve e.g. client=a property would be enough to pickup a **a**DataSource" or **b**DataSource I myself ended up going this approach.
If you have a different application server instance you could just configure a different JNDI path and treat things generically. No need for client="a" property because you have liberty to define your datasource differently with the same name.

Ehcache-Spring-Annotations: How to get cache manager reference?

I am using ehcache-spring-annotations to cache my application data. For this, I have below configuration:
<bean id="ehCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
<ehcache:annotation-driven cache-manager="ehCacheManager" />
I want to get the reference of 'net.sf.ehcache.CacheManager' out of configured bean 'ehCacheManager'. So that, I can manually perform put or remove operations directly in cache using 'CacheManager'.
Any way to get reference of 'net.sf.ehcache.CacheManager' out of 'org.springframework.cache.ehcache.EhCacheManagerFactoryBean'?
I used below code to get the cache manager reference in my class:
#Resource
private CacheManager ehCacheManager;

Spring + Hibernate Search dynamic configuraion

I'm currently trying to configure hibernate search via spring across 3 machines for the purpose of using a JMS distributed index. Due to the way we deploy our software I have to use the same configuration across all three machines but I need a way to set one of them to be the JMS Master.
Currently hibernate is being configured via Spring using the following bean declaration:
<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
id="productSessionFactory">
<property name="dataSource">
<ref local="productDataSource"/>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="entityInterceptor" ref="builderInterceptor"/>
<property name="eventListeners">
<map key-type="java.lang.String" value-type="java.lang.Object">
<entry key="save" value-ref="saveEventListener"/>
</map>
</property>
</bean>
On one of the three machines I need to set the property hibernate.search.default.directory_provider to filesystem-master and on the other two I need to set it to filesystem-slave.
I have the ability to set flags on the individual machines to identify which machine should be the master but due to all the configuration being XML I dont have any ability to add logic to set the parameters correctly.
Is there an way to set this parameter programmatically while leaving the rest of the configuration alone?
Thanks!
A programmatic way is generally possible, but I am not sure exactly how you do that in Spring. Instead of putting your properties into a config file you would have to build the properties dynamically (or at least partly dynamically) and pass it to AnnotationSessionFactoryBean. If I am not mistaken there are hooks in the Spring SPI which should allow you to do that, eg BeanDefinitionRegistryPostProcessor.
The other approach would be to write your own DirectoryProvider. Have a look at org.hibernate.search.store.impl.FSMasterDirectoryProvider and org.hibernate.search.store.impl.FSSlaveDirectoryProvider and write a provider which can act as slave or master depending on the flag you can read on the machine.

Good example of Spring Configuration using java.util.prefs or Commons Configuration

One application I'm working on has several URLs and other information that is instance specific. The first pass uses a typical Spring PropertyPlaceholderConfigurer with a properties file:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:application.properties"/>
</bean>
The main issue with this is of course the property file is an artifact that must be checked in, and for starting a new instance would require updating that artifact. For a streamline deployment, I would like to have the ApplicationContext bootstrap itself based on database table(s). I have seen solutions like this forum post, does anyone here know of better tools or is this defacto approach to this problem? I would also like to be able to update/reload the settings at runtime using JMX or other facilities, but having to restart the app after changes to the database would still be a better solution to the current one.
The way we did it was to put some configuration information in the environment and then pull the relevant info from there.
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="searchSystemEnvironment" value="true" />
</bean>
If configuration changes then the app will need to be restarted. Can also put all the different configurations into the environment and nest the variables like the following:
<bean id="db" class="org.DataSource"
p:databaseServer="${${MODE}_DBSERVER}"
p:databaseName="${${MODE}_DBNAME}" />
where $MODE = dev, qa, etc.

Resources