Mayank Tiwari
Mayank Tiwari

Reputation: 83

How spring batch share data between job

I have one query on Spring Batch Job. I want to share data of one job with another job in same execution context. Is it possible? If so, then how?

My requirement is caching. I have file, where some data is stored. My job runs daily and need data of that file. I don't want to read file by my job daily. instead of it, I want to store data of file in cache(Hash Map). So when same job runs next day, it will use data from cache only. Is it possible in spring batch?

Your suggestion are welcome.

Upvotes: 1

Views: 6060

Answers (3)

Josemy
Josemy

Reputation: 838

Spring have a cache annotation that may help that kind of case and it is really easy to implement. The first call to a method will be executed, afterwards if you call the same method with exactly the same arguments, the value will be returned by the cache.

Here you have a little tutorial: http://www.baeldung.com/spring-cache-tutorial

In your case, if your call to read the file is always with the same arguments will work as you want. Just take care of TTL.

Upvotes: 0

nsylmz
nsylmz

Reputation: 277

You can use spring initialize bean which initializes your cache at startup.

Add initialize bean to your application context;

<bean id="yourCacheBean" class="yourpackage.YourCacheBean" init-method="initialize">
</bean>

YourCacheBean looks like;

public class YourCacheBean {

    private Map<Object, Object> yourCache;

    public void initialize() {
        //TODO: Intialize your cache
    }
}

Give the initialize bean to the itemReader or itemProcessor or itemWriter in job.xml;

<bean id="exampleProcessor" class="yourpackage.ExampleProcessor" scope="step">
    <property name="cacheBean" ref="yourCacheBean" />
</bean>

ExampleProcessor looks like;

public class ExampleProcessor implements ItemProcessor<String, String> {

    private YourCacheBean cacheBean;

    public String process(String arg0) {
        return "";
    }

    public void setCacheBean(YourCacheBean cacheBean) {
        this.cacheBean = cacheBean;
    }
}

Upvotes: 3

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18403

Create a job to import file into database. Other jobs will use data from database as a cache.
Another way may be to read file into a Map<> and serialize object to a file than de-serialize when need (but I still prefer database as cache)

Upvotes: 0

Related Questions