BEIJING — China and Russia signed a $400 billion gas deal on Wednesday, giving Moscow a megamarket for its leading export and linking two major powers that, despite a rocky history of alliances and rivalries, have drawn closer to counter the clout of the United States and Europe.

The impetus to complete the gas deal, which has been talked about as a game-changing accord for more than a decade, finally came together after the Ukrainian crisis forced Russia’s president, Vladimir V. Putin, to urgently seek an alternative to Europe, Moscow’s main energy market. Europe has slapped sanctions on Russia and sought ways to reduce its dependence on Russian energy.

Mr. Putin, on a two-day visit to Shanghai, and the Chinese leader, Xi Jinping, oversaw the signing of the contract between Gazprom and the China National Petroleum Corporation, the biggest natural gas deal Russia has sealed since the collapse of the Soviet Union. The contract runs for 30 years and calls for the construction of pipelines and other infrastructure that will require tens of billions of dollars in investment.

The deal, which Mr. Putin called an “epochal event,” solidified a relationship between China and Russia that had been warming since Mr. Xi assumed power in 2012, as Mr. Xi and Mr. Putin have found common cause.