✍️
Notes.md
  • Table of contents
  • React.Js
    • React Hooks
    • Old :- React : Using Classes
  • Blockchain
    • Solidity
    • Custom ERC20 token
    • Contract
  • Tools and Tech
    • Docker
    • Git version Control
  • Java
    • Data & Data Types
    • IO in Java
    • Data Structures
      • Array in Java
      • Collections in Java
      • Map in Java
      • Enums in Java
      • Linked List in Java
      • List in Java
      • Queues & Stacks
      • Set in Java
      • TreeSet and TreeMap
    • Object Oriented Programming
      • Object Class Methods and Constructor
      • Immutable Class & Objects
      • Constructors
      • Visibility
      • Generics
    • Threads in Java
    • Useful Stuff Java
      • Lambda & Stream
    • Keywords in Java
      • Annotations
      • Comparators
      • Packages in Java
    • Miscellaneous
    • Articles to refer to
  • Golang
    • Competitive Programming in Go
    • Testing simple web server
    • Learning Go : Part 1
    • Maps vs slices
    • Golang Garbage Collector 101
    • Things Golang do differently
    • Go Things
  • Linux
    • Shell programming
    • Linux Commands Part 1 - 4
    • Linux Commands Part 5 - 8
    • Linux Commands Part 9 - 10
  • Software Design
    • Solid Design
    • OOPS
    • Design Patterns
      • Creational Design Pattern
        • Builder DP
        • Factory DP
        • Singleton DP
      • Adapter DP
      • Bridge DP
      • Iterator DP
      • State DP
      • Strategy DP
      • Behavioral Design Pattern
        • Observer DP
      • Structural Design Pattern
        • Facade DP
  • Cloud
    • Google Cloud Platform
      • GCP Core Infrastructure
      • Cloud Networking
  • Spring Boot
    • Spring Basics
      • Spring Beans
      • Important Annotations
      • Important Spring Things
      • Maven Things
      • Spring A.O.P
    • Spring Boot Controller
      • Response Entity Exception Handling
    • Spring Things
    • Spring MVC
    • Spring Data
      • Redis
      • Spring Data JPA
      • JDBC
    • Apache Camel
  • Miscellaneous
    • Troubleshooting and Debugging
Powered by GitBook
On this page
  • Redis with Spring Boot
  • Making class compatible with redis
  • Using Redis as DocStore
  • Enable caching at controller level
  • RedisTemplate for Pub/Sub
  • Redis Stream Publisher template
  • Redis Stream Subscriber template

Was this helpful?

  1. Spring Boot
  2. Spring Data

Redis

working with Redis and Spring Boot

Redis with Spring Boot

@Configuration
@EnableRedisRepositories
public class RedisConfig {

	// configuration for connection
	@Bean
	public JedisConnectionFactory connectionFactory() {
		RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
		// load from properties
		configuration.setHostName("localhost");
		configuration.setPort(6379);
		return new JedisConnectionFactory(configuration);
	}

	// configuration for using redis with java
	@Bean
	public RedisTemplate<String, Object> redisTemplate() {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(connectionFactory());
		template.setKeySerializer(new StringRedisSerializer());
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setHashKeySerializer(new JdkSerializationRedisSerializer());
		template.setValueSerializer(new JdkSerializationRedisSerializer());
		template.setEnableTransactionSupport(true);
		template.afterPropertiesSet();
		return template;
	}

}

Making class compatible with redis

  • Annotate class with : @RedisHash("Product")

  • Implement with Serializable interface

Using Redis as DocStore

  • As docstore because it gives the ability with to search and operate on values

  • To add obj to Redis with id as identifier

redisTemplate.opsForHash().put(HASH_KEY, product.getId(), product);
  • To get all values of obj

redisTemplate.opsForHash().values(HASH_KEY);
  • To get document by id

redisTemplate.opsForHash().get(HASH_KEY, id);
  • To delete obj with id

redisTemplate.opsForHash().delete(HASH_KEY, id);

Enable caching at controller level

  • Annotate with @EnableCaching

  • To enable caching at method level

@Cacheable( key = "#{id}", value = "HASH_KEY", unless = "#result.{field}>{value}" )
  • To remove obj from cache when delete from db

@CacheEvict(key = "#{id}", value = "HASH_KEY")
  • To update obj from cache when delete from db

@CachePut(key = "#{id}", value = "HASH_KEY")

RedisTemplate for Pub/Sub

@Bean
public RedisTemplate<String,Object> template() {
	RedisTemplate<String, Object> template = new RedisTemplate<>();
	template.setConnectionFactory(connectionFactory());
	template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
	return template;
}

@Bean
public ChannelTopic topic() {
	return new ChannelTopic("pubsub:dev117uday");
}

@Bean
public MessageListenerAdapter messageListenerAdapter() {
	return new MessageListenerAdapter(new Receiver());
}

@Bean
public RedisMessageListenerContainer redisMessageListenerContainer( ) {
	RedisMessageListenerContainer container = new RedisMessageListenerContainer();
	container.setConnectionFactory(connectionFactory());
	container.addMessageListener(messageListenerAdapter(), topic());
	return container;
}

Redis Stream Publisher template

Gson gson = new Gson();
var json = gson.toJson(new Users("1", "1", "1"));		
redisTemplate.convertAndSend(topic.getTopic(), json );

Redis Stream Subscriber template

public class RedisReceiver implements MessageListener {

	Logger logger = LoggerFactory.getLogger(RedisReceiver.class);

	@Override
	public void onMessage(Message message, byte[] pattern) {
		try {
			var messageString = getObject(message.getBody());
			Gson gson = new Gson();
			var user = gson.fromJson((String) messageString, Users.class);
			logger.info("Consumed event {}", user.toString());
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}

	}

	private static Object getObject(byte[] byteArr) throws IOException, ClassNotFoundException {
		ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
		ObjectInput in = new ObjectInputStream(bis);
		return in.readObject();
	}

}
PreviousSpring DataNextSpring Data JPA

Last updated 2 years ago

Was this helpful?